Writing Unit Test cases using Mocha and Chai for api written in Nodejs and Express


Author: Gautam Dayal
Published On: Wednesday, May 29, 2024


Following are the steps to create Unit Test cases using Mocha and Chai for api written in Nodejs and Express

image

The following example has been written and tested with Nodejs v18.16.0, Express v4.18.2, Mocha v10.4.0, Chai v4.4.0 and Chai-Http v4.4.0

1. First create a folder called unit-tests. For that run the following command:

sudo mkdir unit-tests

2. Now open the created folder:

cd unit-tests

3. Now run the following command and accept the default values at the prompt:

npm init

4. Now install the required packages:

npm install express@4.18.2 body-parser@1.20.2
npm install chai@4.4.0 chai-http@4.4.0 mocha@10.4.0 nyc@15.1.0 --save-dev

5. Now create a folder called controllers:

sudo mkdir controllers

6. Now open the created folder:

cd controllers

7. Now create a folder called addition:

sudo mkdir addition

8. Now open the created folder:

cd addition
touch index.js

10. Now open the created file:

sudo nano index.js

11. Now paste the below content into the file:

'use strict';

const { Router } = require('express');

const router = Router();

router.post('/addition/add', (req, res) => {
    var num1 = parseInt(req.body.num1);
    var num2 = parseInt(req.body.num2);
    var sum = num1 + num2;

    res.status(200).json({ code: 1, message: 'successfully added 2 numbers', data: sum });
});

module.exports = router;

12. Save and close the file. Now open the root folder of your project:

cd ..
cd ..

13. Now open the index.js file:

sudo nano index.js

14. Now paste the below content into the file:

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const addition = require('./controllers/addition');

const app = express();
const port = 3000;

app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
app.use(addition);

app.listen(port, () => {
    console.log(`${process.env.NODE_ENV} server listening on port: ${port}`);
});

module.exports = app;

15. Save and close the file. Now create a folder called tests:

sudo mkdir tests

16. Now open the created folder:

cd tests

17. Now open file addition.test.js

sudo nano addition.test.js

18. Paste the below content into the file:

const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../index.js');

const expect = chai.expect;

chai.use(chaiHttp);

describe('Test addition of two numbers', () => {
    it('Positive add two numbers', async () => {
        chai.request(server).post('/addition/add').send({
            num1: 10,
            num2: 20
        }).end((err, res) => {
            expect(err).to.be.null;
            expect(res).to.have.status(200);
            expect(res.body.code).to.equal(1);
            expect(res.body.message).to.equal('successfully added 2 numbers');
            expect(res.body.data).to.equal(30);
        });
    });
});

19. Save and close the file. Now go to root of your project:

cd ..

20. Now open package.json file:

sudo nano package.json

21. Replace the value of test within the scripts block with the below value:

NODE_ENV=test nyc mocha 'tests/*.test.js' --timeout 10000

22. Save and close the file. Now run the below command to execute the test cases:

npm run test