mocha before() 中的异步函数总是在 it() 规范之前完成? [英] Async function in mocha before() is alway finished before it() spec?

查看:31
本文介绍了mocha before() 中的异步函数总是在 it() 规范之前完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 before() 中有一个回调函数,用于清理数据库.before() 中的所有内容是否保证在 it() 开始之前完成?

I have a callback function in before() which is for cleaning database. Is everything in before() guaranteed to finish before it() starts?

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 会等待它完成后再继续.例如,以下测试将通过:

You can now return a promise to mocha, and mocha will wait for it to complete before proceeding. For example, the following test will pass :

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 参数,并在回调中调用它.

If you want your asynchronous request to be completed before everything else happens, you need to use the done parameter in your before request, and call it in the callback.

Mocha 将等待直到 done 被调用以开始处理以下块.

Mocha will then wait until done is called to start processing the following blocks.

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

不过你应该小心,因为不为单元测试存根数据库可能会大大减慢执行速度,因为与简单的代码执行相比,数据库中的请求可能相当长.

You should be careful though, as not stubbing the database for unit testing may strongly slow the execution, as requests in a database may be pretty long compared to simple code execution.

有关详细信息,请参阅 Mocha 文档.

For more information, see the Mocha documentation.

这篇关于mocha before() 中的异步函数总是在 it() 规范之前完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆