Back
Close

Tools for Promises Unit Testing

Venkat.R
7,289 views
Previous: Simple Unit Testing Next: Unit Testing with Async.js

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
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
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
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
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants