SSH*_*his 7 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', /json/)
.expect(404, done)
});
Run Code Online (Sandbox Code Playgroud)
我已阅读此处的文档:
https://github.com/visionmedia/supertest
它是这么说的:
请注意如何将 did 直接传递给任何 .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();
});
});
Run Code Online (Sandbox Code Playgroud)
然后测试失败。为什么.expect(200, done)也不失败呢?
根据文档,这符合预期。(https://github.com/visionmedia/supertest)
如果您使用 .end() 方法,则失败的 .expect() 断言不会抛出 - 它们会将断言作为错误返回给 .end() 回调。为了使测试用例失败,您需要重新抛出错误或将错误传递给done()
当您同步做出断言时,您有义务手动处理错误。在您的第一个代码片段中,.expect(404, done)永远不会执行,因为在它到达那里之前抛出了异常。
您的第二个代码段按预期失败,因为它能够处理错误。由于错误已传递给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);
});
Run Code Online (Sandbox Code Playgroud)