我正在尝试为API端点编写一些单元测试,并决定使用带有Supertest的JavaScript Express。我有一些基本的看法,但是在检查特定字段的响应时遇到了问题。我想解析正文,并检查期望的字段是否返回并具有正确的值。我在网上看到的大多数内容都使用此方法,但是当我尝试使用该方法时,即使我输入了值,我仍然知道它在JSON中不存在。有什么建议吗?这是我的代码段:
describe('GET category', function () {
it('response w/ only injury returned', function () {
request('endpoint')
.get('path')
.set('header', 'token')
.expect(200)
.then(response => {
console.assert(response.body, "Baseball")
})
})
});
我还尝试将.then更改为.expect,结果相同。如果我做response.body.specificFieldinBody我得到类似的结果。有帮助吗?
您可以按照自己的方式做-使用.then
语法,但是我认为使用Supertest
断言语法会很好。
这意味着,使用response.body.should.have.property("Baseball");
而不是console.assert(response.body, "Baseball")
(Baseball
是您的特殊字段)。
或者,我的建议是创建重用代码:将断言回调函数放到下一个expects
部分。
const isIncludeField = function (fieldName) {
return function (res) {
res.body.should.have.property(fieldName);
};
}
describe('GET category', function () {
it('response w/ only injury returned', function () {
request('endpoint')
.get('path')
.set('header', 'token')
.expect(200)
.expect(isIncludeField('Baseball')) //
.end(done); // call done callback
})
});