Node.js Supertest预期无法正确断言状态代码
我有一个测试,看起来像这样:Node.js Supertest预期无法正确断言状态代码,node.js,jasmine,supertest,Node.js,Jasmine,Supertest,我有一个测试,看起来像这样: 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',
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)
});
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();
});
});
我已经阅读了这里的文档:
上面说:
请注意如何将done直接传递给任何.expect()调用
不工作的代码行是。expect(404,完成)
如果我将其更改为。expect(200,完成)
则测试不会失败
但是,如果我添加这样一个端点:
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)
});
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)
也没有失败?根据文档,这与预期一样。()
如果您使用的是.end()方法,则失败的.expect()断言不会抛出-它们会将断言作为错误返回给.end()回调。为了使测试用例失败,您需要重新刷新或通过errtodone()
当您同步进行断言时,您有义务手动处理错误。在您的第一个代码段中,.expect(404,done)
永远不会执行,因为在异常到达之前抛出了异常
第二个代码段按预期失败,因为它能够处理错误。当错误被传递给函数(err,res){}
处理程序时
我发现用这种方式处理错误既麻烦又几乎弄巧成拙。因此,更好的方法是使用承诺,这样错误可以自动处理,如下所示:
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);
});
感谢您的回复,这是2.0.0中的突破性变化: