[英]How test multiple async process events with mocha.js
我尝试使用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();
});
您可能需要使用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();
});
});
});
一种方法是使用promise捕获游戏回调的结果:
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内, 由于Mocha在解决时会通过测试,因此仅返回了诺言。 如果他们不解决,他们的测试将拒绝并出现超时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.