Nic*_*.Xu 85 javascript asynchronous mocha.js
我有一个回调函数,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(){
});
Run Code Online (Sandbox Code Playgroud)
Clé*_*hou 123
对于新的mocha版本:
您现在可以向mocha返回一个承诺,mocha将等待它继续完成.例如,以下测试将通过:
let a = 0;
before(() => {
return new Promise((resolve) => {
setTimeout(() => {
a = 1;
resolve();
}, 200);
});
});
it('a should be set to 1', () => {
assert(a === 1);
});
Run Code Online (Sandbox Code Playgroud)
你可以在这里找到文档
对于较旧的摩卡版本:
如果您希望在其他所有事件发生之前完成异步请求,则需要done在before请求中使用该参数,并在回调中调用它.
然后Mocha将等待,直到done调用开始处理以下块.
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() {});
Run Code Online (Sandbox Code Playgroud)
但是你应该小心,因为没有为单元测试存根数据库可能会大大减慢执行速度,因为与简单的代码执行相比,数据库中的请求可能相当长.
有关更多信息,请参阅Mocha文档.
希望您的db.collection()应该返回一个promise。如果是,那么您还可以在before()中使用async关键字
// Note: I am using Mocha 5.2.0.
before(async function(){
await db.collection('user').remove({}, function(res){}); // it is now guaranteed to finish before it()
});
Run Code Online (Sandbox Code Playgroud)