mocha应该期望超时,超时时调用done()

时间:2014-05-18 08:19:30

标签: node.js unit-testing socket.io mocha should.js

我正在尝试为socket编写测试。我正在使用passport.socketio,因此当没有登录用户时,不应连接套接字(因此套接字回调永远不会被触发)。我想测试一下。

有没有办法真正期待超时?

describe('Socket without logged in user', function() {
    it('passport.socketio should never let it connect', function(done) {
        socket.on('connect', function() {
            // this should never happen, is the expected behavior. 
        });
    });
});

或者我应该采取任何其他方式吗?

1 个答案:

答案 0 :(得分:2)

你基本上可以自己编程:

var EXPECTED_TIMEOUT = 2000; // This value should be lesser than the actual mocha test timeout.
it('passport.socketio should never let it connect', function(done) {
    this.timeout(EXPECTED_TIMEOUT + 100); // You add this to make sure mocha test timeout will only happen as a fail-over, when either of the functions haven't called done callback.
    var timeout = setTimeout(done, EXPECTED_TIMEOUT); // This will call done when timeout is reached.
    socket.on('connect', function() {
        clearTimeout(timeout);
        // this should never happen, is the expected behavior.
        done(new Error('Unexpected call'));
    });
});

您还可以使用addTimeout模块缩短代码:

var EXPECTED_TIMEOUT = 2000; // This value should be lesser than the actual mocha test timeout.
it('passport.socketio should never let it connect', function(done) {
    this.timeout(EXPECTED_TIMEOUT + 100); // You add this to make sure mocha test timeout will only happen as a fail-over, when either of the functions haven't called done callback.
    function connectCallback() {
        done(new Error('Unexpected Call'));
    }
    socket.on('connect', addTimeout(EXPECTED_TIMEOUT, connectCallback, function () { 
        done()
    });
});