Testing Web Sockets with Jasmine

坚强是说给别人听的谎言 提交于 2019-12-04 14:08:22

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/18715159/testing-web-sockets-with-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!