![](/img/trans.png)
[英]error with async function in 'before' - testing with mocha and puppeteer
[英]Async function in mocha before() is alway finished before it() spec?
我在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返回一个承诺,mocha将等待它继续完成。 例如,以下测试将通过:
let a = 0;
before(() => {
return new Promise((resolve) => {
setTimeout(() => {
a = 1;
resolve();
}, 200);
});
});
it('a should be set to 1', () => {
assert(a === 1);
});
你可以在这里找到文档
对于较旧的摩卡版本:
如果您希望在其他所有事件发生之前完成异步请求,则需要在before请求中使用done
参数,并在回调中调用它。
然后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() {});
但是你应该小心,因为没有为单元测试存根数据库可能会大大减慢执行速度,因为与简单的代码执行相比,数据库中的请求可能会相当长。
有关更多信息,请参阅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()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.