mocha before()中的异步函数总是在它()规范之前完成?

时间:2014-07-13 13:53:09

标签: javascript asynchronous mocha

我在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(){
});

2 个答案:

答案 0 :(得分:116)

对于新的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);
});

您可以找到文档here

适用于较旧的mocha版本:

如果您希望在其他所有事件发生之前完成异步请求,则需要在之前的请求中使用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 documentation

答案 1 :(得分:3)

希望您的db.collection()应该返回一个承诺。如果是,那么您还可以在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()
});