我在一组 mocha 单元测试中使用了 before 块,并且在其中我正在迭代一组调用以从 REST API 获取信息。我正在使用 chai-http 来执行此操作。但是我遇到的问题是在我发出的一系列ndone()
请求完成之前调用该方法。在 end 块中调用 done 会导致多次调用,但放在块之外意味着它在我真正完成之前就被调用了!这是一个前块的例子:done()
var flags = [];
var groups = [];
// This functions correctly 1 done() called at the end
before(function(done) {
chai.request(server)
.get('/groups')
.end(function(err, res){
groups = JSON.parse(res.text);
done();
});
});
before(function(done) {
groups.forEach(function(rec) {
chai.request(server)
.get('/groups/' + rec.KEYWORD_GROUP_ID + '/groupflags')
.end(function(res, err) {
Array.prototype.push.apply(flags, JSON.parse(res.text));
// A done() here gets called n times
});
// But here it's called before the requests all end
done();
});
有没有办法检测所有这些请求何时完成,然后我可以调用一个done()
来确保我的测试只在正确的上下文设置下执行?