Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async function in mocha before() is alway finished before it() spec?

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(){ }); 
like image 492
Nicolas S.Xu Avatar asked Jul 13 '14 13:07

Nicolas S.Xu


People also ask

Does JavaScript wait for async function to finish?

JavaScript code execution is asynchronous by default, which means that JavaScript won't wait for a function to finish before executing the code below it.

Do async functions return immediately?

With that design, you call the asynchronous function, passing in your callback function. The function returns immediately and calls your callback when the operation is finished. With a promise-based API, the asynchronous function starts the operation and returns a Promise object.

Do async functions run automatically?

In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously.

Do async functions run at the same time?

You can call multiple asynchronous functions without awaiting them. This will execute them in parallel. While doing so, save the returned promises in variables, and await them at some point either individually or using Promise. all() and process the results.


1 Answers

For new mocha versions :

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

You can find the documentation here

For older mocha versions :

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.

like image 95
Clément Berthou Avatar answered Sep 24 '22 22:09

Clément Berthou