如何在没有setTimeout的情况下使用异步Mocha before()初始化? [英] How to use async mocha before() initialization without setTimeout?
问题描述
我正在使用Mocha来测试我创建的一些数据库查询.我需要在block
之前创建适当的外键,以便单元测试可以专注于测试Node ORM的原始创建/删除功能.
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.
我的问题是我在before
块中插入db条目,并且单元测试在before
块完成执行之前正在运行.
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.
我读到了应使用promise处理这类事情,因此我重构了代码库以使用promise,但仍然无法绕开我需要setTimeout的事实.
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.
如何执行异步before
块而无需将我的第一个it
块包装在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);
});
});
推荐答案
您可以像乔伊斯建议那样进行操作.但是,Mocha支持使用诺言进行同步.您必须兑现您的诺言:
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)
});
});
在能够对代码返回的诺言执行.then
之前,Mocha不会继续进行测试.
Mocha won't continue to the test until it is able to execute .then
on the promise returned by your code.
这篇关于如何在没有setTimeout的情况下使用异步Mocha before()初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!