Search code examples
javascriptnode.jsexpresssupertest

How to test key and value of object using supertest module


I have test code as below:

const mocha = require('mocha');
const describe = mocha.describe;
const it = mocha.it;
const chai = require('chai');
const request = require('supertest');

const app = require('../app.test');

chai.should();

describe('Get /histories', () => {
  it('should return 200 status code', done => {
    request(app)
      .get('/client/profile')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });

  it('should return code: 400', done => {
    request(app)
      .get('/client/profile')
      .expect('Content-Type', /json/)
      .expect(200)
      .expect(res => {});
  });
});

And I respond with a custom status code using Express:

return res.json({
    code: 400
})

Therefore I want to test that test code has code as key of object and the value is 400 as number.

How can I write this test?


Solution

  • You could use this:

    it('should return code: 400', (done) => {
      request(app)
        .get('/client/profile')
        .expect('Content-Type', /json/)
        .expect(200)
        .end((err, res) => {
          if (err) {
            return done(err);
          }
          expect(res.code).to.be.equal(400);
          return done();
        });
    });