我该如何执行asynchronous摩卡testing(NodeJS)?

这个问题涉及到NodeJS的Mochatesting框架。

默认行为似乎是开始所有的testing,然后处理asynchronouscallback,因为他们进来。

在运行asynchronoustesting时,我希望在调用之前的asynchronous部分之后运行每个testing。

我怎样才能做到这一点?

重点不在于“结构化代码按照您构build的顺序运行”(令人吃惊!) – 而是如@ chrisdew所示,asynchronoustesting的返回订单不能得到保证。 要重申这个问题 – 进一步在(同步执行)链下的testing不能保证所有由asynchronoustesting设置的条件在运行的时候就准备好了。

因此,如果您要求在第一次testing中设置某些条件(如login令牌或类似条件),则必须使用像before()那样的钩子,以便在继续之前设置testing条件。

将相关testing包装在一个块中, before挂钩before运行一个asynchronous (注意before块中的“完成”):

 var someCondition = false // ... your Async tests setting conditions go up here... describe('is dependent on someCondition', function(){ // Polls `someCondition` every 1s var check = function(done) { if (someCondition) done(); else setTimeout( function(){ check(done) }, 1000 ); } before(function( done ){ check( done ); }); it('should get here ONLY once someCondition is true', function(){ // Only gets here once `someCondition` is satisfied }); }) 

我对你写的东西感到惊讶。 我使用摩卡与bdd风格testing(描述/它),只是添加了一些console.logs到我的testing,看看你的要求与我的情况下,但似乎他们没有。

这是我用来查看“end1”和“start1”顺序的代码片段。 他们正确地下令。

 describe('Characters start a work', function(){ before(function(){ sinon.stub(statusapp, 'create_message'); }); after(function(){ statusapp.create_message.restore(); }); it('creates the events and sends out a message', function(done){ draftwork.start_job(function(err, work){ statusapp.create_message.callCount.should.equal(1); draftwork.get('events').length.should.equal( statusapp.module('jobs').Jobs.get(draftwork.get('job_id')).get('nbr_events') ); console.log('end1'); done(); }); }); it('triggers work:start event', function(done){ console.log('start2'); statusapp.app.bind('work:start', function(work){ work.id.should.equal(draftwork.id); statusapp.app.off('work:start'); done(); }); 

当然,这也可能是偶然发生的,但是我有很多的testing,如果他们能够平行运行,我肯定会有比赛条件,我没有。

请从摩卡问题跟踪器中查看这个问题 。 据此,testing是同步运行的。

我想用我们的应用程序解决同样的问题,但是接受的答案对我们来说并不合适。 特别是在someCondition情况下永远不会是真的。

我们在我们的应用程序中使用promise,这使得testing的结构非常简单。 但是关键还是要通过挂钩延迟执行:

 var assert = require( "assert" ); describe( "Application", function() { var application = require( __dirname + "/../app.js" ); var bootPromise = application.boot(); describe( "#boot()", function() { it( "should start without errors", function() { return bootPromise; } ); } ); describe( "#shutdown()", function() { before( function() { return bootPromise; } ); it( "should be able to shut down cleanly", function() { return application.shutdown(); } ); } ); } ); 

使用摩卡步骤

它会保持testing的顺序,无论它们是否是asynchronous的(即你的function仍然是一样的)。 这是一个直接替代it ,而是你使用step