Вопрос

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.

Это было полезно?

Решение

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

Другие советы

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top