当前位置: 动力学知识库 > 问答 > 编程问答 >

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

});

});

网友答案:

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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: