簡體   English   中英

如何使用mocha.js測試多個異步流程事件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM