Tools for Promises Unit Testing

Venkat.R
2,067 views

Open Source Your Knowledge, Become a Contributor

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

Create Content
Previous: Unit Testing with Dependent Files

Async.js

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with Node.js and installable via npm install --save async, it can also be used directly in the browser.

In this below example, We use async.parallel where we need to trigger the DB Service Method at the same time.

Service File
1
2
3
4
5
6
7
8
9
10
11
12
13
const async = require('async');
const db = require('./db');
function myAsyncParallel (callback) {
async.parallel({
first: db.userData.bind(null, 'first arg'),
second: db.activityData.bind(null, 'second arg')
}, callback);
}
module.exports = {
myAsyncParallel,
};
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Unit Testing

Similar to Previous example, Added Mocha, Chai and Sinon and added only one example for success scenario.

Mainly we are by passing the DB Methods db.userData and db.activityData and return the custom data using Sinon Stub.

In this test case, we are checking the expected result is deeply equal to the method response.

Unit Testing with Async.js
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
const mocha = require('mocha');
const expect = require('chai').expect;
const sinon = require('sinon');
const db = require('./db');
const asyncFile = require('./parallel');
describe('Async Parallel.js', () => {
let params, resultValues, userDataStub, activityDataStub, activityDataSpy;
before(() => {
params = ['first arg', 'second arg'];
resultValues = ['First Result', 'Second Result'];
});
beforeEach(() => {
userDataStub = sinon.stub(db, 'userData').callsFake((arg, callback) => {
callback(null, {
arg,
result: resultValues[0]
});
});
activityDataStub = sinon.stub(db, 'activityData').callsFake((arg, callback) => {
callback(null, {
arg,
result: resultValues[1]
});
});
});
it('should return the response', () => {
return asyncFile.myAsyncParallel(function(error, results) {
expect(results).to.deep.equal({
first: {
arg: params[0],
result: resultValues[0]
},
second: {
arg: params[1],
result: resultValues[1]
}
});
});
});
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Cool, Isn’t it !!

Happy Coding, Stay tuned for next one !

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content