我尝试用mocha.js测试一些异步进程事件。默认情况下,it方法在done调用后执行synchronious。使用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();
});发布于 2015-04-18 00:00:29
您可能需要使用the ()钩子来正确设置测试。试试这个:
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();
});
});
});发布于 2016-05-25 23:37:44
一种方法是使用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函数为调用回调时解析的每个事件创建新的promises。由于游戏尚未开始,事件处理程序已正确注册。
在it块中,promises只是返回since mocha will pass the test when they resolve。如果它们不能解决,它们的测试将拒绝,并显示超时错误。
https://stackoverflow.com/questions/29703353
复制相似问题