Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute async Mocha tests (NodeJS) in order?

This question relates to the Mocha testing framework for NodeJS.

The default behaviour seems to be to start all the tests, then process the async callbacks as they come in.

When running async tests, I would like to run each test after the async part of the one before has been called.

How can I do this?

like image 509
fadedbee Avatar asked Mar 16 '12 11:03

fadedbee


People also ask

Do Mocha tests run sequentially?

According to it, tests are run synchronously. This only shows that ordered code is run in order. That doesn't happen by accident.

How do you test async in Mocha?

Writing Asynchronous Tests with Mocha. To indicate that a test is asynchronous in Mocha, you simply pass a callback as the first argument to the it() method: it('should be asynchronous', function(done) { setTimeout(function() { done(); }, 500); });

How do I run a specific test file in Mocha?

If you want to run all the test cases which are inside one describe section, then you can also write only to describe as well. describe. only('<Description of the tests under this section>', function() { // ... }); If you have multiple test files & you wanted to run only one of then you can follow the below command.


2 Answers

The point is not so much that "structured code runs in the order you've structured it" (amaze!) - but rather as @chrisdew suggests, the return orders for async tests cannot be guaranteed. To restate the problem - tests that are further down the (synchronous execution) chain cannot guarantee that required conditions, set by async tests, will be ready they by the time they run.

So if you are requiring certain conditions to be set in the first tests (like a login token or similar), you have to use hooks like before() that test those conditions are set before proceeding.

Wrap the dependent tests in a block and run an async before hook on them (notice the 'done' in the before block):

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   });  }) 
like image 53
papercowboy Avatar answered Oct 15 '22 03:10

papercowboy


use mocha-steps

it keeps tests sequential regardless if they are async or not (i.e. your done functions still work exactly as they did). It's a direct replacement for it and instead you use step

like image 41
WiR3D Avatar answered Oct 15 '22 02:10

WiR3D