Search code examples
node.jschai

Other response codes then 200 in Chai


Im new to Chai. What I understand, in order to make the tests work, the routes should always return http code 200. Is that correct? As soon as I have a route returning other then 200 I get errors in test suite (for example Uncaught Error: Internal Server Error).

In my routes, when passed data is wrong (for example validation) I would like to return other codes than 200. I think I read somewhere that it can be good practice to return other codes than 200 for resources that are not returning OK (for example vaidation errors or database errors). But again it seems that I have to return 200 for making Chai tests work. Am I missing something or it really needs to be 200 all the time?


Solution

  • No, it doesn't have to be 200. You need to use the callback syntax, and notice it uses the errors first callback style. If you expect an error then just make your test pass if the error is correct. For example

      it('fails, as expected', function(done) { // <= Pass in done callback
      chai.request('http://localhost:8080')
      .get('/')
      .end(function(err, res) {
        expect(res).to.have.status(400);
        done();                               // <= Call done to signal callback end
      });
    });
    

    This is from the chai-http docs. https://github.com/chaijs/chai-http/blob/master/README.md