An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
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
- Install dependencies
npm i mocha -g (global install)npm i chai mocha request -D (local install)
- 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')});
- 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.
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.
Original Link: https://dev.to/imranmind/easy-way-to-write-unit-test-cases-of-nodejs-3p6n
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To