Tools for Promises Unit Testing

Venkat.R
1,258 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Promise with dependent Files.

In Real time, Long files used to be split into number of small files as models, libs and services. Here, We will see service File which is included the db helper file where we get the DB data.

Service File
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const db = require('./db');
function getResultData(name) {
let payload;
if (name) {
payload = {
prop1: `value1-${name}`,
prop2: `value2-${name}`,
};
}
return new Promise((resolve, reject) => {
db.getData(payload).then((data) => {
if (data.error) {
reject(data);
}
resolve(data);
});
});
}
module.exports = {
getResultData,
};
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
DB Helper File
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function getData(payload) {
return new Promise((resolve, reject) => {
if(!payload) {
reject({
error: true,
});
}
setTimeout(() => {
resolve({
name1: 'value1',
name2: 'value2',
});
}, 5000);
});
}
module.exports = {
getData,
};
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Unit Testing

This Unit Testing included Mocha, Chai and Sinon Libraries and included file like Service and DB Helper.

Here, you can notice there is before, beforeEach, after hook were added for method request params and response with Sinon Stubs. It actually helps to proxy the calls of DB Library.

Why we need Sinon?

SinonJS has many good features. Below are few methods and we used for Stubs.

Service File Unit Testing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const mocha = require('mocha');
const expect = require('chai').expect;
const sinon = require('sinon');
const db = require('./db');
const service = require('./service');
describe('service.js', () => {
let noop, label, payload, response, dbStub;
before(() => {
noop = () => {};
label = 'emp';
payload;
response;
dbStub;
});
beforeEach(() => {
payload = {
prop1: `value1-${label}`,
prop2: `value2-${label}`,
};
response = {
name1: 'value1',
name2: 'value2',
};
dbStub = sinon.stub(db, 'getData').callsFake(() => {
return Promise.resolve(response);
});
});
afterEach(() => {
dbStub.restore();
});
it('should return error response', () => {
return service.getResultData().then(noop, (data) => {
expect(data).to.deep.equal({
error: true,
});
});
});
it('should return success response', () => {
return service.getResultData(label).then((data) => {
expect(data).to.deep.equal(response);
});
});
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content