Test a Node RESTful API with Mocha and Chai
In this article we will see, how we will test our rest API via mocha and chai, I am assuming that you know the mocha and chai, if you still need then I am providing the link.
Mocha — Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun
Chai — Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.
Prerequisites
- First, we need a basic node js project with one basic API.
- Some dev dependencies, which are given below.
"chai": "^4.3.7",
"chai-http": "^4.3.0",
"mocha": "^10.2.0",
"mochawesome": "^7.1.3",
"sinon": "^15.0.1",
Kindly follow these steps.
Step 1:- First will set up the folder for the unit test cases which will be the unit-test, as you can see in the given structure.
Inside unit-test we can manage both mock data and test cases based on our project structure.
Step 2:- Now time to set up the script inside the package.json file like this.
"unit-test": "mocha 'unit-test/test-cases/**/*.spec.js'",
Step 3:- Will write one route for the unit test case, if you don't have any route/api.
Route
// Load required modules
const express = require('express');
const cloudAgent = require('../controllers/cloud');
// Default settings
const router = express.Router();
// Routes list for cloud_agent
router.get('/health', cloudAgent.health);
module.exports = router;
Controller
'use strict';
//load required modules
//const msg = require('../utils/lang/messages');
//const logger = require('../utils/log');
//api for health checkup
exports.health = async (req, res) => {
console.log('Service Healthy');
res.send({
code: "200",
message: "Service Healthy",
});
}
Curl for this API
curl --location --request GET 'http://localhost:3001/health'
Response for API
{
"code": "200",
"message": "Service Healthy"
}
Step 4:- Will write the test case for the above route/api.
save this file inside the unit-test folder.
'use strict';
const chai = require('chai'); // for assert
let chaiHttp = require('chai-http');
const expect = chai.expect; // type of assert
const sinon = require("sinon"); // function mocking
chai.use(chaiHttp);
// Load configurations
const config = require('../../../config/cloud_agent');
const server = require('../../../app');
/* Sample test case */
describe('Sample test-case', () => {
it("Sample test case for the project", async function () {
this.timeout(3000);
return expect("data").to.be.a('string');
});
// Run hook after each and every tets-case
afterEach(function () {
sinon.restore(); // Unwraps the spy
});
});
/* Health api test case */
describe("/health", () => {
it("Health api test case", async function () {
this.timeout(3000);
try {
let res = await chai.request('http://localhost:3001').get(config.unit_testing.api.health);
expect(res).have.status(200);
expect(res.body).to.be.a('object');
return;
} catch (error) {
throw (new Error(error));
}
});
// Run hook after each and every tets-case
afterEach(function () {
sinon.restore(); // Unwraps the spy
});
});
Step 5:- Now, time to run the test cases.
Will run the complete test case which all are inside the test-case/test-cases folder via the given command.
npm run unit-test
And it will look like this.
That’s it for this time! I hope you enjoyed this post. As always, I welcome questions, notes, comments and requests for posts on topics you’d like to read. See you next time! Happy Coding !!!!!