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 :
Prerequisite:
There are some frameworks or libraries for testing purpose in Node.js , that we can use for unit testing:
Here Iโm gonna show you how can we create unit test with the combination of Mocha and Chai Testing Framework.
What is Mocha ?
# Installs globally npm install -g mocha # installs in the current directory npm install mocha
What is chai ?
# installs globally npm install -g chai # installs in local directory as a dev dependency npm install chai
Environment Setup:
"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:
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.
/* 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); }) }) });
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.
// 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(); }) }) }); })
> 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.????????
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular