Skip to content Skip to sidebar Skip to footer

How To Use Async Mocha Before() Initialization Without SetTimeout?

I am using Mocha to test out some database queries I created. I need my before block to create the appropriate foreign keys so the unit tests can focus on testing out the raw creat

Solution 1:

You could do it like joews suggests. However, Mocha supports using promises for synchronization. You have to return your promise:

before(function() {
    var token = '' + Math.random();
    return models.createUser(token).then(function() {
      testMessage.userToken = token;
      models.insert(testMessage)
    });
});

Mocha won't continue to the test until it is able to execute .then on the promise returned by your code.


Solution 2:

The function you pass to before, like the other Mocha API methods, can accept a done callback. You should call this when your before actions have completed:

before(function(done) {
  var token = '' + Math.random();
  models.createUser(token).then(function() {
    testMessage.userToken = token;
    return models.insert(testMessage)
  }).then(function() {
    done();
  })
});

Mocha docs - asynchronous code


Post a Comment for "How To Use Async Mocha Before() Initialization Without SetTimeout?"