它()规范之前异步功能摩卡()之前常是完了吗? [英] Async function in mocha before() is alway finished before it() spec?

查看:147
本文介绍了它()规范之前异步功能摩卡()之前常是完了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前在的回调函数()这是清洁的数据库。
一切都在()之前保证前来完成它()开始?

 之前(函数(){
   db.collection(用户),删除({}功能(RES){})。 //它是保证之前完成()?
});它('测试规范',函数(完成){
  //做测试
});后(函数(){
});


解决方案

如果您想一切发生之前完成你的异步请求,您需要使用完成在你的面前请求参数,并调用它的回调。

然后

摩卡会等到完成被调用,以开始处理以下块。

 之前(功能(完成){
   。db.collection(用户),删除({}功能(RES){进行();}); //现在它保证之前完成'它'开始。
})它('测试规范',函数(完成){
  //执行测试
});后(函数(){});

您要小心,尽量不要存根单元测试数据库可能放缓强烈的执行,如在数据库请求可能是pretty长相比于简单的code执行。

有关更多信息,请参见摩卡文档

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

解决方案

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 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.

For more information, see the Mocha documentation.

这篇关于它()规范之前异步功能摩卡()之前常是完了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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