Reputation: 8426
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(){}));
});
Upvotes: 17
Views: 27584
Reputation: 815
I created a file __mocks__/ws.js
:
const {WebSocket} = require("mock-socket");
module.exports = WebSocket
See note from jest-websocket-mock:
// mocks/ws.js
export { WebSocket as default } from "mock-socket";
the mock should be placed in the
__mocks__
directory ... and will be automatically mocked.
Upvotes: 0
Reputation: 1545
Use mock-socket
package and then global
to make it available for nodejs:
import { WebSocket } from 'mock-socket';
global.WebSocket = WebSocket;
Upvotes: 17
Reputation: 110972
In jest, you need to add stuff that should be available in the global scope aka window
, to the global
namespace:
global.WebSocket= WebSocket
Upvotes: 12