Node.js

Unit Testing In Node JS With Chai And Mocha

In this blog , we will discuss how we can run test case in Node.js applications with mocha and chai testing framework.

Some Brief Intro :

  • Node.js is a widely used JavaScript runtime environment that allows JavaScript to run on server or more accurately on back end.
  • Unit Testing is a way of testing software applications with test every component or element in precise way, this will help us to catch some bugs in applications that arenโ€™t identify by normal methods.

Prerequisite:

  • Basic Knowledge Node.js, JavaScript , NPM , Node File Structure

There are some frameworks or libraries for testing purpose in Node.js , that we can use for unit testing:

  • Mocha
  • Jest
  • Jasmine
  • AVA
  • Chai

Here Iโ€™m gonna show you how can we create unit test with the combination of Mocha and Chai Testing Framework.

What is Mocha ?

  • Mocha is one of the oldest and widely used testing framework for Node runtime environment.
    It supports asynchronous way of operations like callbacks, promises, and async/await.
    It is highly modifiable and we can combine it with other testing frameworks for better performence.To install it,type the following command on Command Prompt:
# Installs globally
npm install -g mocha
# installs in the current directory
npm install mocha

What is chai ?

  • Chai is a BDD(Behavior Driven Development) / TDD(Test Driven Development) assertion library/framework for node and browsers that we can pair it with other testing frameworks
# installs globally
npm install -g chai
# installs in local directory as a dev dependency
npm install chai

Environment Setup:

  • Now , we are gonna first add a command to run mocha test in script array of package.json file
"scripts": {
      "test": "mocha test.js", // Here test.js is file where we are gonna write test cases 
      "dev": "nodemon index.js",
      "serve": "node index.js",     
     }

Letโ€™s first create test.js file.

Import some dependency that required for to use chai and mocha framework.

// Here assert will help us to create test cases 
var assert = require('chai').assert;
// To use chai framework
const chai = require('chai');
// It's used to get response and send request to an api, that we can use for testing
let chaiHttp = require('chai-http');
// add middleware to use httpchai
chai.use(chaiHttp);
// this api url is on my localhost that is created in Express framework with Node Runtime
let server = 'http://localhost:8000/posts'

To run tests:

  • Use npm run test command to run test
npm run test

Here are some Example that how we can create simple test cases.

In First example , we are gonna test if an array has an element or not.

  • In this example we are gonna find element 4 from an array list , which isnโ€™t available in array,
    so it will gonna return -1.
/* Here We will test if an array contain specified element or not, 
from that outcome we will gonna printout something on terminal
*/describe('Array',function(){
    describe('#IndexOf()',function(){
        it('It should return -1 when the value is not present',function(){
            assert.equal([1,2,3].indexOf(4),-1);
        })
    })
});
  • describe() as name suggest this function used to describe block of test, in this block we can add some condition and test cases.
  • it() it is means individual test case, in this we can apply text that can be display on terminal after the test meet the criteria.
  • assert : This keyword is used compare or create assumption based on condition that you are gonna apply,
    think this way you are telling to assert that this comparison gonna give me this kind of output.
  • Now Run this command in terminal : npm run test
  • It will give you this kind of output
mocha test.js


  Array
    #IndexOf()
      โœ” It should return -1 when the value is not present


  1 passing (6ms)

In Second Example , we are gonna do something interesting.

  • Here we are gonna make an API request.
  • This API will require JWT token for authentication.
  • If We donโ€™t pass Authorization header with Bearer token with , the api will gonna give us 401 status , with body
    that tell us that auth is false and a message with โ€˜No token provided.โ€™
  • For this , we are gonna write test case if our api request doesnโ€™t contain Authorization header
    we should get above mentioned response from api.
// Check Auth if Token is not provided
describe('Authorization',()=>{
    describe('/Get posts without Token',()=>{
        it('It should get 401 unauthorized response if token is not sent with request',(done)=>{
            chai.request(server)
            .get('/')            
            .end((err,res)=>{
                assert.equal(res.status,401)
                assert.equal(res.body.auth,false)                                
                assert.equal(res.body.message,'No token provided.')                                                
                done();            
            })
        })
    });
})
  • Now run command , npm run test and you could get this kind of output in terminal
> mocha test.js



  Authorization
    /Get posts without Token
      โœ” It should get 401 unauthorized response if token is not sent with request


  1 passing (42ms)

Thatโ€™s How We can create simple test case in Node.js application.

I hope that this kind of thing you can use in your projects.????????

Karan Rajgor

I am .NET Core and Angular Developer. My favorites programming languges are Typescript,Javascript,C#,SQL. I love to work on statically type programming languages. For entertainment i watch anime and play games. That's all about me ๐Ÿ˜๐Ÿ˜๐Ÿ˜๐Ÿ˜

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago