jeudi 28 janvier 2016

Testing Socket.io Event Handler using Sinon

I am trying to make a functional test of a socket.io event handler. To make it simple, we will just look on the 'connect' event on the client.

Suppose:

MyClass.prototype.onConnected = function(){ console.log('hello'); }
MyClass.prototype.connect = function() {
     this.socket.connect(...params...);
};
...
// Later on in the instance `myclass`
...
sinon.spy(this, 'onConnected');
...
this.socket.on('connect', this.onConnected);

The above code is supposed to attach a sinon spy to the 'connect' event handler of the socketio-client. Therefore, I would like to make a test which could assert like:

describe(...
     it('should connect', function(){
          myClass.connect();
          myClass.onConnected.should.have.been.called;
     }
     ...
);

Now I see the problem with the ticks here. Assertation is executed way before the socket.io sends the connect event. Therefore, test fails. One way around this is using timers or setTimeout to let some time pass between the connect call and the assertation. But I have no way of knowing how long the response will be delayed. Suppose I have 1000 tests like this, then this would make me wait hundreds of seconds till the test-suite finishes! Another problem is that, at that time my computer could be loaded so much that socketio may respond much later than usual. In that case, faketimers wont work at all.

Is there a nice, neat solution for this problem? I have been looking at the chai-as-promised, which utilizes the eventually keyword. But it won't solve my case either without uglifying all the code with promise resolvers (and also, I won't be able to check how many times the eventHandler is called etc...) Please help!

Aucun commentaire:

Enregistrer un commentaire