Ashutosh
Ashutosh

Reputation: 4675

Mocha tests cases not waiting before to complete

I'm writing test cases with mocha in Nodejs and want to reset database data before running the tests. I'm using Knex as query builder for executing queries.

I wrote following logic:

describe('Activities:', function() {

  before(funtion(){
   activityDBOperations.deleteAll()
   .then(function(){
       // all records are deleted
   });
  });

  it('it should add a record into Activities table: multiple time activity',  function(done) {
    activityDBOperations.addRecord(requestParams)
        .then(function(data) {
            expect(data.length > 0).to.equal(true);
            done();
        });
  });
});

The problem is that test cases start executing and not waiting for deleteAll operation to finish. What I understand is since deleteAll is returning promise, the program execution move forward because of asynchronous nature of promises.

How can I make sure that test cases should run only when deleteAll has finished?

Upvotes: 5

Views: 4763

Answers (2)

Sergey Lapin
Sergey Lapin

Reputation: 2693

Either provide a callback to your before hook and call it in then:

before(function(done) {
   activityDBOperations.deleteAll()
     .then(function() {
         // all records are deleted
         done();
     });
});

or, according to Mocha docs, just return a promise from before:

before(function() {
   return activityDBOperations.deleteAll();
});

Upvotes: 4

Jason Livesay
Jason Livesay

Reputation: 6377

Add return statements so the Promises are actually returned.

Upvotes: -1

Related Questions