简体   繁体   English

Mocking WebSocket 在开玩笑

[英]Mocking WebSocket in Jest

I'm trying to test a library that uses WebSockets.我正在尝试测试使用 WebSockets 的库。 I'm trying to mock the websocket using the code below.我正在尝试使用下面的代码模拟 websocket。 The library ROSController uses web sockets, but I keep getting the WebSocket is not defined.ROSController使用 web sockets,但我一直收到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: 使用mock-socket包然后使用global来使其可用于nodejs:

import { WebSocket } from 'mock-socket';

global.WebSocket = WebSocket;

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

global.WebSocket= WebSocket

I created a file __mocks__/ws.js :我创建了一个文件__mocks__/ws.js

const {WebSocket} = require("mock-socket");

module.exports = WebSocket

See note from jest-websocket-mock :请参阅jest-websocket-mock 的说明:

// mocks /ws.js //模拟/ws.js

export { WebSocket as default } from "mock-socket";从“模拟套接字”导出 { WebSocket 作为默认值};

And the manual-mocks docs :手动模拟文档

the mock should be placed in the __mocks__ directory... and will be automatically mocked.模拟应该放在__mocks__目录中......并且会自动模拟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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