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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much .I'll go through it.
You are welcome! With any doubt I can help you. Also if the answer solve your problem, mark it as accepted is appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.