DEV Community

Imran shaikh
Imran shaikh

Posted on

Easy way to write Unit Test cases of Node.Js

Initially, I used to think why my Architect is asking for writing test cases it's just wasting of time, But later I realised that it's important to write test cases along with the application features . Because it will give you the confidence in each iteration of new build or release.

I have seen the impact of not writing proper test cases in one of my projects, As the developer is always hurrying for completing user stories or features. As I have analyzed we could have stopped at least 40% bugs if we would have written the proper unit test cases.

So let's see the easy way to write Node.Js unit test cases Using Mocha and Chai library

Mocha is a test runner environment

Chai is an assertion library

1.Create node.js project using:

npm init
Enter fullscreen mode Exit fullscreen mode
  1. Install dependencies
npm i mocha -g (global install)

npm i chai mocha request -D (local install)
Enter fullscreen mode Exit fullscreen mode
  1. Create app.js file and write the below code.
const express = require('express');
const app = express();
app.get('/ping', (req, res)=>{
  res.status(200);
  res.json({message: 'pong'});
});
app.listen(8080, ()=>{
  console.log('Waw Server is running : 8080')
});
Enter fullscreen mode Exit fullscreen mode
  1. create a test folder and add app.test.js file and write the below code.
var expect = require('chai').expect;
var request = require('request');
describe('app rest api testing', () => {
  it('/ping status code', (done) => {
    request('http://localhost:8080/ping', (err, result, body) => {
    expect(result.statusCode).to.equal(200);
    expect(body).to.equal(JSON.stringify({"message":"pong"}));
    done();
  });
 });
});
Enter fullscreen mode Exit fullscreen mode

Before running an application make sure you configure everything in package.json file like below.

Image description

after that run your application using the below command

npm run test
Enter fullscreen mode Exit fullscreen mode

:) Now you can see the output of test cases. like the below image.

I always welcome the new approach so feel free to add a comment regarding the new approach.

Thanks for reading. :)

Please hit the love button if you liked it.

Image description

Top comments (0)