我在 before()
中有一个回调函数,用于清理数据库。
before()
中的所有内容是否保证在 it()
开始之前完成?
before(function(){
db.collection('user').remove({}, function(res){}); // is it guaranteed to finish before it()?
});
it('test spec', function(done){
// do the test
});
after(function(){
});
最佳答案
对于新的 mocha 版本:
您现在可以向 mocha 返回一个 promise,mocha 将等待它完成后再继续。例如,以下测试将通过:
let a = 0;
before(() => {
return new Promise((resolve) => {
setTimeout(() => {
a = 1;
resolve();
}, 200);
});
});
it('a should be set to 1', () => {
assert(a === 1);
});
您可以找到文档 here
对于较旧的 mocha 版本:
如果您希望您的异步请求在其他一切发生之前完成,您需要在您的 before 请求中使用 done
参数,并在回调中调用它。
然后 Mocha 将等待直到 done
被调用以开始处理以下 block 。
before(function (done) {
db.collection('user').remove({}, function (res) { done(); }); // It is now guaranteed to finish before 'it' starts.
})
it('test spec', function (done) {
// execute test
});
after(function() {});
不过你应该小心,因为不为单元测试 stub 可能会大大减慢执行速度,因为与简单的代码执行相比,数据库中的请求可能相当长。
有关详细信息,请参阅 Mocha documentation .
关于javascript - mocha before() 中的异步函数总是在 it() 规范之前完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24723374/