Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking WebSocket in Jest

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

});
like image 970
cjds Avatar asked Mar 17 '17 21:03

cjds


People also ask

How do you mock WebSockets?

To be able to mock the WebSocket connection, we need to create an instance of the Server. import { Server } from 'mock-socket'; const websocketServer = new Server('ws://localhost:5000'); The mock-socket library also has the socket.io support.

Where do you put the jest mock?

If the module you are mocking is a Node module (e.g.: lodash ), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.


2 Answers

Use mock-socket package and then global to make it available for nodejs:

import { WebSocket } from 'mock-socket';

global.WebSocket = WebSocket;
like image 147
Marios Fakiolas Avatar answered Sep 21 '22 05:09

Marios Fakiolas


In jest, you need to add stuff that should be available in the global scope aka window, to the global namespace:

global.WebSocket= WebSocket
like image 24
Andreas Köberle Avatar answered Sep 21 '22 05:09

Andreas Köberle