简体   繁体   中英

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

});

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

import { WebSocket } from 'mock-socket';

global.WebSocket = WebSocket;

在jest中,您需要将全局范围aka window中应该可用的内容添加到global命名空间:

global.WebSocket= WebSocket

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";

And the manual-mocks docs :

the mock should be placed in the __mocks__ directory... and will be automatically mocked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM