Back
Close

Tools for Promises Unit Testing

Venkat.R
7,199 views
Previous: Introduction Next: Simple Unit Testing

MochaJs

Mocha is a JavaScript test framework running on node.js, featuring browser support, asynchronous testing, test coverage reports, and use of any assertion library. It can be used with libraires like should.js, expect.js and chai.js.

Simple Mocha Example
const mocha = require('mocha');
describe('Simple Testing', () => {
describe('Basic', () => {
it('Test Case 1', () => {
});
it('Test Case 2', () => {
});
it('Test Case 2', () => {
});
});
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

ChaiJs

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

Simple Chai Example
const mocha = require('mocha');
const expect = require('chai').expect;
describe('Simple Chai Testing', () => {
describe('Basic', () => {
it('Test Case 1', () => {
expect(1+1).to.equal(2);
});
it('Test Case 2', () => {
expect(typeof (1+1)).to.equal('number');
});
it('Test Case 2', () => {
const response = {
a: {
b: ['x', 'y']
}
};
expect(response).to.have.nested.property('a.b[1]');
});
});
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

SinonJs

SinonJs is a standalone library for test spies, stubs and mocks for JavaScript. Works with any unit testing framework.

Simple Sinon Example
const dbStub = sinon.stub(db, 'getData').callsFake(() => {
return Promise.resolve(response);
});
const dbSpyy = sinon.spy(db, 'getData');
expect(db.getData(0).args[0]).to.deep.equal({
success: true,
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Installation

Use below any one command to install Mocha, Chai and Sinon Module and these must to be installed as Dev Dependencies modules, because it’s not required when application running in the server but during build.

$ npm i -D mocha chai sinon
            or
$ npm install mocha chai sinon --save-dev

Code Coverage

If you are very much interested on how much code covered during unit testing. Try Istanbul which make test coverage simple with various types of report format.

$ npm i -D nyc
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