我尝试使用mocha.js测试一些异步进程事件。 it
方法默认情况下在done
调用后执行同步。使用mocha.js
describe('Game', function(done){
var game = new Simulation.Game();
this.timeout(5000);
it('should start', function(done){
game.on('start', function() {
done();
});
});
it('should log', function(done){
game.on('log', function() {
done();
});
});
it('should end', function(done){
game.on('end', function() {
done();
});
});
game.start();
});
答案 0 :(得分:3)
您可能需要使用before()挂钩来正确设置测试。试试这个:
describe('Game', function(){
var game;
this.timeout(5000);
before(function(before_done) {
game = new Simulation.Game();
game.start();
before_done();
};
it('should start', function(done){
game.on('start', function() {
done();
});
});
it('should log', function(done){
game.on('log', function() {
done();
});
});
it('should end', function(done){
game.on('end', function() {
done();
});
});
});
答案 1 :(得分:1)
一种方法是使用promises来捕获游戏回调的结果:
describe('Game', function(done){
var started, logged, ended;
// Wrapping the initialization code in a before() block
// allows subsequent describe blocks to be run if an
// exception is thrown.
before(function () {
var game = new Simulation.Game();
var game_on = function (event) {
return new Promise(function (resolve, reject) {
game.on(event, function () {
resolve();
});
});
};
started = game_on('start');
logged = game_on('log');
ended = game_on('end');
game.start();
});
this.timeout(5000);
it('should start', function(){
return started;
});
it('should log', function(){
return logged;
});
it('should end', function(){
return ended;
});
});
game_on函数为每个在调用回调时解析的事件创建新的promise。由于游戏尚未开始,因此事件处理程序已正确注册。
在it-blocks中,承诺只返回since mocha will pass the test when they resolve。如果他们没有解决,他们的测试将拒绝超时错误。