Unit testing with Mocha & Chai for Node env. and Istanbul for code coverage

Unit testing with Mocha & Chai for Node env.
Mocha
Mocha is a JavaScript test framework for Node.js. For more details and documentation check its Github repo. To install mocha check below cmd:
npm install mocha --save-dev


Chai Chai is an assertion library, similar to Node’s build in assert. It makes testing much easier by giving you lots of assertions you can run against your code. For more details and documentation check its Github repo. To install Chai check below cmd:
npm install chai --save-dev
Chai provides both BDD (Behaviour Driven Development) as well as TDD (Test Driven Development) assertion style.
The Expect / Should API covers the BDD assertion styles.
The Assert API covers the TDD assertion style.

Istanbul
Istanbul provides code coverage report either on command line or as html report. For more details and documentation check its Github repo. To install mocha check below cmd:
npm install nyc --save-dev



Some other important links are:
scotch.io
sinon cheatsheet
sinon summary



Steps to setup test:
Step 1: Create new test folder and add new test file. ex. index.spec.js Step 2: Now in spec file set NODE_ENV to test. ex. process.env.NODE_ENV = 'test'; Step 3: Import dev dependencies at top of the file.
// local dependencies
const chai = require('chai');
const { expect } = chai;
const sinon = require('sinon');
step 4: Writting test
describe('{method name}', () => {
it('{test description}', () => {
// test code here
});
});



Note: run before and after test to initialize and cleanup the test.


Running unit test: 1) using Mocha:
./node_modules/mocha/bin/mocha test/index.spec.js

2) using npm (package.json):
"test": "./node_modules/mocha/bin/mocha tests/**/*test.js --reporter spec"

Comments