Supertest期望不正确地声明状态码

我有一个像这样的testing:

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) }); 

我已经阅读了这里的文档:

https://github.com/visionmedia/supertest

它说:

注意如何直接传递给任何.expect()调用

不工作的代码行是.expect(404, done)如果我改变这个.expect(200, done)那么testing不会失败。

但是,如果我添加这样的结尾:

  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(); }); }); 

然后testing失败。 为什么.expect(200, done)也不失败?

根据文件,这是预期的。 ( https://github.com/visionmedia/supertest

如果使用.end()方法,那么失败的.expect()断言不会抛出 – 它们会将断言作为错误返回给.end()callback。 为了失败testing用例,您需要重新抛出或通过err完成()

当你同步的断言时,你有义务手动处理错误。 在你的第一个代码片段中, .expect(404, done)永远不会被执行,因为在它到达之前抛出exception。

您的第二个片段按预期的方式失败,因为它能够处理该错误。 由于错误已传递给function(err, res) {}处理程序。

我觉得这样做很麻烦,而且几乎要弄巧成拙。 所以更好的方法是使用promise,以便可以自动处理错误,如下所示:

 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); });