我有一个看起来像这样的测试:
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)
,那么测试不会失败。
但是,如果我添加这样的结尾:
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();
});
});
然后测试失败。为什么.expect(200, done)
也没有失败?
答案 0 :(得分:2)
根据文件,这是预期的。 (https://github.com/visionmedia/supertest)
如果使用.end()方法.expect()失败的断言不会抛出 - 它们会将断言作为错误返回给.end()回调。为了使测试用例失败,您需要重新抛出或将错误传递给done()
当您同步进行断言时,您有义务手动处理错误。在您的第一个代码段中,.expect(404, done)
永远不会被执行,因为在它到达之前抛出了异常。
您的第二个代码段失败,因为它能够处理错误。由于错误已传递给function(err, res) {}
处理程序。
我发现以这种方式处理错误很麻烦且几乎弄巧成拙。因此,更好的方法是使用promises,以便可以按如下方式自动处理错误:
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);
});