Api test automation with mocha and chai

Mocha is a JavaScript test framework running on Node.js and in the browser, which can be used for unit testing, and api and ui automated testing, here we will use it along with chai to do some api automated testing in nodejs with typescript.

Packages

We will install packages below with yarn add or npm install

  • @types/chai-http
  • @types/mocha
  • @types/node
  • chai
  • chai-http
  • mocha
  • mochawesome
  • ts-mocha
  • ts-node
  • typescript
  • typings

Writing tests

Mocha BDD interface will be used to create the test case. chai-http

describe('test get findByStatus', () => {

    it(`should succeed when findByStatus`, (done) => {
        chai.request(baseUrl)
        .get('/v2/pet/findByStatus')
        .query({status:'available'})
        .end(function(err,res){
            expect(res).to.have.status(200);
            expect(res.body).to.to.have.length(432);
            done();
           });

    }).timeout(30000);

});
describe('test get findByStatus', () => {

    it(`should succeed when findByStatus-async`, async () => {
        const res = await chai.request(baseUrl)
        .get('/v2/pet/findByStatus')
        .query({status:'available'});
        expect(res).to.have.status(200);
        expect(res.body).to.to.have.length(4320);

    }).timeout(30000);

});

Data driven

We have created one test case, but we have some more status to check, so let’s make it data driven.

describe('test get findByStatus', () => {

    var tests : {status:string, expectedCount: number } [] = [
        {status:"available", expectedCount:1000},
        {status:"pending", expectedCount:300},
        {status:"sold", expectedCount:500}
    ];

    tests.forEach(function(test) 
    {
        it(`should succeed when findByStatus - ${test.status}`, async () => {
            const res = await chai.request(baseUrl)
            .get('/v2/pet/findByStatus')
            .query({status:'available'});
            expect(res).to.have.status(200);
            expect(res.body).to.to.have.length(test.expectedCount);
    
        }).timeout(30000);

    });
});

Execution and reporting

//Add content below in the scripts section of package.json
"test": "ts-mocha --file src/test/tw.test.ts",
"test:report": "ts-mocha  --reporter mochawesome --file src/test/tw.test.ts"