I am trying to write tests to ensure that my Express API is correctly returning the right HTTP status codes for various scenarios. I am using Mocha, and Supertest for requests to the API in the tests. Right now I'm getting very unexpected results, which are detailed below.
Using: Express, body-parser, Sequelize, Mocha, Supertest
GET /users/:id
models.User.find(req.params.id).complete(function(err, foundUser) {
if (err) {
logger.error(err, 'Error');
return err;
}
console.log('user: ' + foundUser);
if (foundUser != null) {
res.json({ user: foundUser.getJsonRepresentation() });
}
else {
res.status(404);
res.json({ error: 'Not found' });
}
});
Tests for this method
it('responds with the right user', function(done){
request(app)
.get(apiPath + '/users/' + createdUser.id)
.set('Accept', 'application/json')
.expect(function(res) {
res.body.user.id.should.equal(createdUser.id);
})
.expect(200, done);
});
it('responds with the right error code for non-existent resource', function(done) {
request(app)
.get(apiPath + '/users/1000')
.expect(404, function(err, res) {
console.log(err);
console.log('Response: ' + res);
done();
});
});
For the 404 test, I get this error: { [Error: Parse Error] bytesParsed: 12, code: 'HPE_INVALID_STATUS' }
in the callback. The res
is undefined
.
I have tried several different syntax forms for this expect
call: .expect(404, function(err, res) {
and none of them have worked. I've also tried all the different syntax forms for this as well:
res.status(404);
res.json({ error: 'Not found' });
Can anyone offer some insight into what is going on here?
Maybe the issue is in the following code snippet:
if (err) {
logger.error(err, 'Error');
return err;
}
It seems to be triggering the error but not actually returning it to the supertest
client.
You can try to return the error to the client instead of only logging it, like this:
if (err) {
logger.error(err, 'Error');
res
.status(500);
.json({ error: error.message });
return err;
}