嘲笑WebSocket [英] Mocking WebSocket in Jest
本文介绍了嘲笑WebSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试测试使用WebSockets的库.我正在尝试使用下面的代码来模拟websocket.库ROSController
使用Web套接字,但是我一直在获取WebSocket is not defined.
I'm trying to test a library that uses WebSockets. I'm trying to mock the websocket using the code below. The library ROSController
uses web sockets, but I keep getting the WebSocket is not defined.
import { ROSController } from '../ROSController.jsx';
var socketMock;
var windowMock;
var address = 'ws://test.address';
beforeAll(function() {
var WebSocket = jasmine.createSpy();
WebSocket.and.callFake(function (url) {
socketMock = {
url: url,
readyState: WebSocket.CONNECTING,
send: jasmine.createSpy(),
close: jasmine.createSpy().and.callFake(function () {
socketMock.readyState = WebSocket.CLOSING;
}),
// methods to mock the internal behaviour of the real WebSocket
_open: function () {
socketMock.readyState = WebSocket.OPEN;
socketMock.onopen && socketMock.onopen();
},
_message: function (msg) {
socketMock.onmessage && socketMock.onmessage({data: msg});
},
_error: function () {
socketMock.readyState = WebSocket.CLOSED;
socketMock.onerror && socketMock.onerror();
},
_close: function () {
socketMock.readyState = WebSocket.CLOSED;
socketMock.onclose && socketMock.onclose();
}
};
return socketMock;
});
WebSocket.CONNECTING = 0;
WebSocket.OPEN = 1;
WebSocket.CLOSING = 2;
WebSocket.CLOSED = 3;
windowMock = {
WebSocket: WebSocket
};
return WebSocket;
});
test('the subscription JSON produced is correct', () => {
console.log(WebSocket); //<----- It fails here
JSON.parse((new ROSController('')).callService('/test','', function(){}));
});
推荐答案
在玩笑中,您需要将在全局范围(又称为window
)中应该可用的内容添加到global
命名空间:
In jest, you need to add stuff that should be available in the global scope aka window
, to the global
namespace:
global.WebSocket= WebSocket
这篇关于嘲笑WebSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文