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 create/delete functionality of my Node ORM.
My problem is that I am inserting db entries in my before
block and the unit tests are running before the before
block is finished executing.
I read that promises should be used to deal with this kind of thing, so I refactored my codebase to use promises but I still can't get around the fact that I need a setTimeout.
How can I perform async before
block without needing to wrap my first it
block in a setTimeout
?
var chai = require('chai');
var expect = chai.expect;
var db = require('../server/db/config');
var models = require('../server/db/models');
describe('scoring', function() {
var testMessage = {
x: 37.783599,
y: -122.408974,
z: 69,
message: 'Brooks was here'
};
var messageId = 1;
before(function() {
var token = '' + Math.random();
models.createUser(token).then(function() {
testMessage.userToken = token;
models.insert(testMessage)
});
});
it('should have votes created in db when createVote is called', function(done) {
setTimeout(function(done) {
models.createVote(messageId, token, function(err, res) {
expect(res.insertId).to.be.a('number');
done();
});
}.bind(this, done), 1000);
});
});
The function you pass to
before
, like the other Mocha API methods, can accept adone
callback. You should call this when yourbefore
actions have completed:Mocha docs - asynchronous code
You could do it like joews suggests. However, Mocha supports using promises for synchronization. You have to return your promise:
Mocha won't continue to the test until it is able to execute
.then
on the promise returned by your code.