我在 chai 测试中遇到了 http 响应问题,我不知道如何才能获得 res.body 的长度,除非通过 console.log。
这是我要运行的测试:
it('It should have a length of 3061', function(){
chai.request('http://localhost:8080')
.get('/api/pac/')
.end(function(err,res){
console.log(res.body.length); //it shows 3061
expect(res.body).to.have.lengthOf(3061); //it causes error "Cannot read property 'body' of undefined"
});
});
如果我尝试对 res.body 进行期望,它会返回“无法读取未定义的属性‘body’”。但是 console.log 有效。
console.log(res.body) 显示一个包含 3061 个对象的 json。每个对象都有这样的结构:
iid : {type : Number},
dnas : [{ _id : Number,
col : Date,
reproved : {type : Boolean},
wave : {type: Number,
index: true}
}],
name : { type : String,
uppercase: true,
index: true}
最佳答案
您需要将 done
传递给您的 it
回调,因为 chai.request('http://localhost:8080').get()
是异步的。没有它,您将尝试在 it
完成后运行断言。换句话说,您需要告诉 它
等待 HTTP get 请求完成。注意,我正在使用一些 es6。如果您的项目不支持 es6,请将我的箭头替换为回调函数。
it('should have a length of 3061', done => {
chai.request('http://localhost:8080')
.get('/api/pac/')
.end((err, res) => {
if (err) done(err);
expect(res.body).to.have.lengthOf(3061);
done();
});
});
关于javascript - http get 请求的 Mocha/Chai 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44953016/