問(wèn)題描述
這是一些使用 stomp 協(xié)議為 web-socket 編寫(xiě)的代碼.
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) {
};
我找到了這篇文章,但它需要實(shí)際連接到服務(wù)器,單元測(cè)試Node.js和WebSockets (Socket.io)
I found this post but it requires actual connection to server, Unit testing Node.js and WebSockets (Socket.io)
我們?nèi)绾问褂?Jasmine 進(jìn)行測(cè)試.尋找一種偽造網(wǎng)絡(luò)套接字服務(wù)器和觸發(fā)事件(連接、斷開(kāi)連接等)的方法.我將不勝感激任何示例或有用的鏈接.
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.
推薦答案
只需模擬函數(shù)的所有依賴項(xiàng),因此在您的情況下,這將是 SockJS
和 Stomp.over代碼>.
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)
運(yùn)行腳本后,您可以測(cè)試他們被調(diào)用的間諜.要運(yùn)行回調(diào)函數(shù),您可以使用 mostRecentCall.args
找到它們并在測(cè)試中調(diào)用它們:
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();
這篇關(guān)于使用 Jasmine 測(cè)試 Web 套接字的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!