Basic unit test of nodejs using mochajs framework

Node js is a server side scripting language. Today we are developing a lot of application using nodejs. As, our code base increases we also need to test our code regularly. Here today, we are going to discuss, how to test our nodejs code  using the mocha framework. Watch below video :


Basic steps To follow for testing node application:

1)Create a folder myapp

mkdir myapp

2)Go inside the myapp folder

cd myapp

3)Create folder utils

create calculator.js

module.exports.add = (a,b)=>{

return a+b;


module.exports.subtract = (a,b) =>{

return a-b;


module.exports.multiply = (a,b)=>{

return (a*b);


module.exports.divide = (a,b) =>{

return (a/b);


Note : module.exports keyword is used so, that other module can access it.

MochaJs Test framework : It is a javascript test framework.It runs the test serially.

Ref :

To install mocha run bellow command :

npm i mocha@3.0.0 –save

Now, create calculator.test.js

it() function  : It is a function provided by mochajs framework. Inside it we can define our new test case. It contains the 2 arguments. First one the testcase name . Another os callback function. This is known as behaviour based development (BDD).

var calc = require('./calculator.js');

it('Test for add function ', () => {

  var ans1 = calc.add(1, 2);

  if (ans1 != 3) {

      throw new Error("Addition error");



it('Test for subtract function ',()=>{

  var ans2 = calc.subtract(9,2);

  if(ans2 != 7){

      throw new Error("Subtraction error");



it("Test for multiply function ",()=>{

  var ans3 = calc.multiply(2,3);


      throw new Error("Multiply error");



it("Test for divide function ",()=>{

var ans4 = calc.divide(14,2);


  throw new Error("Divide error");



Note : Above, we are not using any assertion library for testing. We are simply throwing error if the answer is not according to our expectation. Next after this topic , we will look into the assertion library.

After , creating our test file . We need to go to package.json file


“name”: “node_test_2”,

“version”: “1.0.0”,

“description”: “”,

“main”: “index.js”,

“scripts”: {

  “test”: “echo \”Error: no test specified\” && exit 1


“author”: “”,

“license”: “ISC”,

“dependencies”: {

  “express”: “^4.16.3”,

  “mocha”: “^5.2.0”



Above , the test key value pair contains  echo \”Error: no test specified\” && exit 1

We need to replace it by :

mocha *.test.js

“scripts”: {

  “test”: “mocha *.test.js


After all above setting. Now, it is time to run our test case

npm run test

Pankaj-Agarwal:node_test_2 pankaj.agarwal$ npm run test

Pankaj-Agarwal:node_test_2 pankaj.agarwal$ npm run test

> node_test_2@1.0.0 test /Users/pankaj.agarwal/Documents/pankaj/practice/node_test_2

> mocha *.test.js

 ✓ Test for add function

 ✓ Test for subtract function

 ✓ Test for multiply function

 ✓ Test for divide function

 4 passing (9ms)

Auto run test suit : 

For this install nodemon globally.

npm i nodemon -g

Ref :

In package.json, let us include a new key:value (test-watch) pair

“scripts”: {

  “test”: “mocha *.test.js”,

test-watch” : “nodemon –exec ‘npm test’”


The above code, will execute the test automatically, whenever any code changes happens

Now, on the cmd type :

npm run test-watch

Using The assertion library :

Assertion library will make assumption about the value.Earlier we are using if condition it(‘Test for add function ‘, () => {

  var ans1 = calc.add(1, 2);

  if (ans1 != 3) {

      throw new Error(“Addition error”);



Now, we will not use the if condition , but we will use assertion library

Note : Please follow the reference documentation for clear explanation

Ref :

Some of the assertion functions are below:






To install expect :

npm install expect –save

After installation , we can see it’s entry inside the package.json

“dependencies”: {

  “expect”: “^23.4.0”,

  “mocha”: “^5.2.0”


Now, include the expect inside the calculator.test.js

var expect = require(‘expect’);
Now, let us see some of examples :


Now, let us see some of examples :

it(‘Test for add function ‘, () => {

  var ans1 = calc.add(2,5);

  expect(typeof ans1).toBe(‘number’);

  // if (ans1 != 3) {

  //    throw new Error(“Addition error”);

  // }

Ex2 : not.toBe()

it(“Test for not equal ”,()=>{



Ex3 : toEqual()

To test the object we have to use :

it(“Test object equal “,()=>{

  expect({name : ‘Mohan’}).toEqual({name : ‘Mohan’})


Ex4 :not.toEqual()

it(‘Test for not equal for object ‘,()=>{

expect({name : ‘Mohan’}).not.toEqual({name : ‘mohan’});


Test our nodejs express application using mocha :

For this, first of all write an express application

We will use supertest to test our application. Supertest is made by the same team that developed the express

Ref :

Let us create a new express application :

Our express code :

var express = require(‘express’);

var app = express();

var route = express.Router();


res.send(‘Hello world’)





console.log(‘The server runs at 3000 ‘)

}); = app; (This is important , so that we can use it in other module)


Out test file :

Let us create a test file for our express server

const request = require(‘supertest’);

var app = require(‘./server.js’).app;

var request = require(‘request’);

it(‘should return hello world response ‘,(done)=>{

request(app).get(‘/api/’).expect(‘Hello world’).end(done);


To Check status code also :



.expect(‘Hello world’).end(done);


Leave a reply:

Site Footer