LogaKrishnan
LogaKrishnan

Reputation: 501

handle different responses using mocha in nodejs unit testing

my test is getting passed(200 status code), when i passing correct header information. but when i try with wrong info(400 status code), it can't able to handle that error,

this is my code,(here im passing wrong headers info, so response will be status 400 code)

const chai = require('chai');
const expect = require('chai').expect;
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const main  = require('../server');
let token;
describe('GET USER', function()  {
  this.timeout(50000);
  it('Display info about user and returns a 200 response', (done) => {
    chai.request(main)
    .get('/users')
    .set("Authorization"," ")
    .then(function(response) {
      // Now let's check our response
      expect(response).to.have.status(200);
      done();
    })
    .catch((err)=>{
      expect(err.status).to.be.equal(400)
      done();
    })
  });
});

im getting error like this,

GET USER
(node:28390) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected undefined to equal 400
    1) Display info about user and returns a 200 response

  1 failing

  1) GET USER
       Display info about user and returns a 200 response:
     Error: Timeout of 50000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/test/users.test.js)

Upvotes: 1

Views: 1746

Answers (2)

Estus Flask
Estus Flask

Reputation: 222334

As mentioned in another answer, you can't test 200 and 400 at the same time.

Calling done() prior to expect will result in test timeout if an assertion fails, because it throws assertion error and done is never called. This results in unhandled rejection, because there's no another catch after catch.

chai-http supports promise control flow. Mocha naturally handles promises, a test should return a promise instead of using done. As it's suggested, error response can be reached as err.response. It likely should be:

describe('GET USER', function()  {
  it('should returns 400 response', () => {
    return chai.request(main)
    .get('/users')
    .set("Invalid header"," ")
    .catch(function(err) {
      expect(err.response.status).to.have.status(400);
    });
  });
});

Upvotes: 2

Yan Foto
Yan Foto

Reputation: 11378

There seems to be a small misunderstanding here: the catch is not executed if chai-http receives an HTTP error. It is executed if the request fails. Getting 200 or 400 should both be tested in then and not catch.

As you can see from the error message, the err object does not have a status field because its not a response object but an instance of Error.

Upvotes: 1

Related Questions