Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
Ashutosh Avatar asked Oct 17 '22 18:10

Ashutosh


1 Answers

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();
});
like image 132
Sergey Lapin Avatar answered Nov 15 '22 07:11

Sergey Lapin