Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 24, 2021 09:43 am GMT

Easy way to write Unit Test cases ofNode.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
  1. Install dependencies
npm i mocha -g (global install)npm i chai mocha request -D (local install)
  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')});
  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();  }); });});

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

:) 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


Original Link: https://dev.to/imranmind/easy-way-to-write-unit-test-cases-of-nodejs-3p6n

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To