首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用mocha.js测试多个异步进程事件

如何使用mocha.js测试多个异步进程事件
EN

Stack Overflow用户
提问于 2015-04-17 23:24:39
回答 2查看 2.9K关注 0票数 0

我尝试用mocha.js测试一些异步进程事件。默认情况下,it方法在done调用后执行synchronious。使用mocha.js测试多个异步进程的策略是什么

代码语言:javascript
复制
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();
});
EN

回答 2

Stack Overflow用户

发布于 2015-04-18 00:00:29

您可能需要使用the ()钩子来正确设置测试。试试这个:

代码语言:javascript
复制
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();
        });
      });
});
票数 3
EN

Stack Overflow用户

发布于 2016-05-25 23:37:44

一种方法是使用promises来捕获游戏回调的结果:

代码语言:javascript
复制
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。如果它们不能解决,它们的测试将拒绝,并显示超时错误。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29703353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档