2

I'm trying to write a test for socket. I'm using passport.socketio and so socket shouldn't be connected (and thus the socket callback never fired) when there's no logged in user. I want to test that.

Is there a way to actually expect a timeout?

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

Or any other way I should approach this?

laggingreflex
  • 32,948
  • 35
  • 141
  • 196

1 Answers1

4

You can basically program it yourself:

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

You can also use addTimeout module to shorten the code:

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()
    });
});
Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115