首页 > 解决方案 > Jest with WebSockets 会忽略第一个消息之后的消息吗?

问题描述

我正在尝试测试 WebSockets 服务器。onMessage 处理程序仅在第一次被调用 - 发布到服务器的任何进一步消息都不会被记录。为什么会这样?`

     const WebSocket = require('ws');
     const ws = new WebSocket(WEBSOCKETS_ENDPOINT);

     describe('When a speed test is triggered', () => {
     test('Then AWS should send the result to the client', done => {
        ws.on('open', async () => {
            ws.send(JSON.stringify({
                message: 'start-speed-test-rbsid',
                data: RBSID,
                platform: "android"
            }));
                ws.on('message', data => {
                    data = JSON.parse(data)
                    // this gets called only once - any further messages published from the server are not logged
                    console.log(data)
                });
        })
     })
     afterAll(() => ws.close())

});

消息数据应记录在已发布的每条消息上

标签: javascriptwebsocketjestjs

解决方案


我对回显服务器使用您的代码没有问题。

const WebSocket = require('ws');
const ws = new WebSocket('wss://echo.websocket.org');

describe('When a speed test is triggered', () => {
  test('Then AWS should send the result to the client', done => {
    ws.on('open', async () => {
      ws.send(JSON.stringify({
        message: 'start-speed-test-rbsid',
        data: 'RBSID',
        platform: "android"
      }));
      ws.on('message', data => {
        // this gets called only once - any further messages published from the server are not logged
        console.log(data)
      });

      ws.send(JSON.stringify({
        message: 'start-speed-test-rbsid',
        data: 'RBSID',
        platform: "android"
      }));
    })
  })
  afterAll(() => ws.close());
});

还有一点是,如果你在写单元测试,并且测试涉及到网络 IO,通常建议模拟网络组件。

const WebSocket = require('ws');

jest.mock('ws', () => {
  class MockedWebSocket {}

  return MockedWebSocket;
});

console.log(WebSocket); // mocked

推荐阅读