简体   繁体   中英

How test multiple async process events with mocha.js

I try to test some async process events with mocha.js. The it method executes synchronious after done call by default. What is the strategy to test multiple async processes with 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();
});

You probably need to use the before() hook to set up the test properly. Try this:

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();
        });
      });
});

One way is to use promises to capture the result of the game callbacks:

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;
    });
});

The game_on function creates new promises for each event that resolve when the callbacks are called. The event handlers are registered correctly since the game has not yet started.

Inside the it-blocks the promises are just returned since mocha will pass the test when they resolve . If they do not resolve, they tests will reject with a timeout error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM