Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Web Sockets with Jasmine

Here is some code that has been written for web-socket using stomp protocol.

function WS(url) {
    var ws = new SockJS('/notifications');

    this.client = Stomp.over(ws),

    this.client.connect('', '', function() {
        console.log('Connected');
    }, function(error) {
        console.log('STOMP protocol error: ', error.headers.message);
    });
}

WS.prototype.disconnect = function() {
};

WS.prototype.subscribe = function() {
};

WS.prototype.unSubscribe = function() {
};

WS.prototype.send = function(msg) {
};

I found this post but it requires actual connection to server, Unit testing Node.js and WebSockets (Socket.io)

How do we test this using Jasmine. Looking for a way to fake web-socket server and fire events (connect, disconnect etc). I'll appreciate any example or useful link.

like image 959
RuntimeException Avatar asked Mar 03 '26 03:03

RuntimeException


2 Answers

Just mock all your dependencies of your function, so in your case this will be SockJS and Stomp.over.

var wsSpy = jasmine.createSpy();
spyOn(window, 'SockJs').andReturn(wsSpy);

var clientSpy = jasmine.createSpy();
spyOne(Stomp, 'over').andReturn(clientSpy)

After running your script you can test on the spies that they was called. To run the callback functions you can use mostRecentCall.args to find them and call them in the test:

var successCallBack = clientSpy.mostRecentCall.args[2];
successCallBack();

var errorCallBack = clientSpy.mostRecentCall.args[3];
errorCallBack();
like image 63
Andreas Köberle Avatar answered Mar 05 '26 15:03

Andreas Köberle


Just an update to Andreas accepted answer. The syntax for this has change in Jasmine as per http://jasmine.github.io/2.3/introduction.html#section-31

The new syntax as per Jasmine 2.3 would be:

clientSpy.calls.mostRecent().args
like image 24
perry Avatar answered Mar 05 '26 15:03

perry