Saya mencoba menguji perpustakaan yang menggunakan WebSockets. Saya mencoba mengejek soket web menggunakan kode di bawah ini. Pustaka ROSController menggunakan soket web, tetapi saya tetap mendapatkan 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(){}));

});
15
cjds 18 Maret 2017, 00:12

2 jawaban

Jawaban Terbaik

Dalam bercanda, Anda perlu menambahkan hal-hal yang harus tersedia dalam lingkup global alias window, ke namespace global:

global.WebSocket= WebSocket
5
Andreas Köberle 20 Maret 2017, 07:18

Gunakan paket mock-socket dan kemudian global untuk membuatnya tersedia untuk nodejs:

import { WebSocket } from 'mock-socket';

global.WebSocket = WebSocket;
15
Marios Fakiolas 28 September 2017, 11:35