0

I want to write unit testing for my REST API calls(Using mocha and chai). Can anyone provide me better guide or any previously written code ,so that I can perform easily.

1 Answer 1

1

There are multiple guides through internet to start with mocha and chai. As, for example, the official documentation:

Using npm you can install both:

  • Mocha: npm install --save-dev mocha
  • Chai: npm install chai

Also, for HTTP you need chai-http: npm install chai-http

With this you can start to code your tests.

First of all, into your test file you need import packages

var chai = require('chai'), chaiHttp = require('chai-http');

chai.use(chaiHttp);

And also use the assertion you want, for example:

var expect = chai.expect;.

Tests use this schema:

describe('Test', () => {
    it("test1", () => {
    })

    it("test2", () => {
    })
})

Where describe is to declare a 'suite' of tests. And inside every suite you can place multiple tests, even another suite.

If you execute this code using mocha yourFile.js you will get:

Test
    √ test1
    √ test2

Now you can start to add routes to test. For example somthing like this:

it("test1", () => {
    chai.request('yourURL')
    .get('/yourEndpoint')
    .query({value1: 'value1', value2: 'value2'})
    .end(function (err, res) {
        expect(err).to.be.null;
        expect(res).to.have.status(200);
    });
})

And if you want to use your own express app, you can use

var app = require('../your/app')

... 

it("test1", () => {
    chai.request(app)
    ...
}
...

And also exists multiple more options describe into Chai documentation.

2
  • Thank you very much .I'll go through it. Commented Nov 5, 2020 at 10:17
  • You are welcome! With any doubt I can help you. Also if the answer solve your problem, mark it as accepted is appreciated.
    – J.F.
    Commented Nov 7, 2020 at 14:52

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.