Reputation: 111
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.
Upvotes: 0
Views: 1035
Reputation: 15187
There are multiple guides through internet to start with mocha
and chai
. As, for example, the official documentation:
Using npm
you can install both:
npm install --save-dev mocha
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.
Upvotes: 1