Reputation: 1929
I have a test that looks like this:
it('should fail to get deleted customer', function(done) {
request(app)
.get('/customers/'+newCustomerId)
.set('Authorization', 'Bearer ' + token)
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(404, done)
});
I've read the documentation here:
https://github.com/visionmedia/supertest
It says this:
note how you can pass done straight to any of the .expect() calls
The line of code that isn't working is .expect(404, done)
if I change this to be .expect(200, done)
then the test doesn't fail.
However, if I add an end like this:
it('should fail to get deleted customer', function(done) {
request(app)
.get('/customers/'+newCustomerId)
.set('Authorization', 'Bearer ' + token)
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end(function(err, res) {
if (err) console.log(err);
done();
});
});
Then the test fails. Why is .expect(200, done)
not failing also?
Upvotes: 7
Views: 5467
Reputation: 500
This is as expected, according to the documentation. (https://github.com/visionmedia/supertest)
If you are using the .end() method .expect() assertions that fail will not throw - they will return the assertion as an error to the .end() callback. In order to fail the test case, you will need to rethrow or pass err to done()
When you are making your assertions synchronously, it is your obligation to handle the errors manually. In your first code snippet, .expect(404, done)
never gets executed, because an exception was thrown before it got there.
Your second snippet fails as expected because it is able to handle the error. As the error was passed to the function(err, res) {}
handler.
I find it cumbersome and almost self-defeating to have to handle errors this way. So the better way is to use promises, so that the errors can be handled automatically as follows:
it('should fail to get deleted customer', function() {
return request(app)
.get('/customers/'+newCustomerId)
.set('Authorization', 'Bearer ' + token)
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200);
});
Upvotes: 6