简体   繁体   English

JestJS - 多个 websocket 连接挂起 Jest

[英]JestJS - Multiple websocket connections hangs Jest

I'm using this function to test my server that creates as many websocket connections and checks when my game starts.我正在使用这个函数来测试我的服务器,它创建了尽可能多的 websocket 连接并检查我的游戏何时开始。 However no matter the timeout I assign, it hangs on JestJS.但是,无论我分配的超时时间如何,它都会挂在 JestJS 上。 On the browser - Firefox, Edge Chromium it works perfectly fine.在浏览器 - Firefox,Edge Chromium 上它运行得非常好。

function checkGameStart(numberOfBots) {
    return new Promise((resolve, reject) => {
        let clients = [];
        let connection = [];
        for (let i = 0; i < numberOfBots; i++) {
            clients.push(new WebSocket('ws://127.0.0.1:8080'));
            connection.push(false);
            clients[i].onmessage = (msg) => {
                let data = JSON.parse(msg.data);
                if (data.title === "gameStarted") {
                    connection[i] = true;
                    checkAllClientsReady();
                }
            }
            clients[i].onerror = (err) => reject(err);
        }
        function checkAllClientsReady() {
            if (!(connection.includes(false))) {
                resolve(true);
                closeAllConnections();
            }
        }
        function closeAllConnections() {
            for (let i = 0; i < clients; i++) {
                clients[i].close()
            }
        }
    });
}

Does anyone know why it happens what I can do to make sure it doesn't happen again.有谁知道它为什么会发生,我可以做些什么来确保它不再发生。

Test code;测试代码;

test('Check the game starts', () => {
    return expect(checkGameStart(4)).resolves.toBe(true);
});

I refactored your code a little bit and added a WebSocket server using ws NPM package on the test setup:我稍微重构了你的代码,并在测试设置中使用ws NPM 包添加了一个 WebSocket 服务器:

const { WebSocketServer } = require('ws')

const port = 8080
const wss = new WebSocketServer({ port })

beforeAll(() => {
  wss.on('connection', (ws) => {
    ws.send(JSON.stringify({ title: 'gameStarted' }))
  })
})
afterAll(() => {
  wss.close()
})

async function checkGameStart(numberOfBots) {
  await Promise.all(
    new Array(numberOfBots).fill(null)
      .map(() => new Promise((resolve, reject) => {
        const ws = new WebSocket(`ws://localhost:${port}`)

        ws.onmessage = ({ data }) => {
          const { title } = JSON.parse(data)
          if (title === 'gameStarted') {
            ws.close()
            resolve()
          }
        }

        ws.onerror = (err) => {
          ws.close()
          reject(err)
        }
      }))
  )
  return true
}

test('Check the game starts', async () => {
  await expect(checkGameStart(4)).resolves.toBe(true);
});

$ npx jest
 PASS  ./websocket.test.js
  ✓ Check the game starts (64 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.708 s, estimated 1 s
Ran all test suites.

This only works if Jest is also configured to use a jsdom test environment :这仅在 Jest 还配置为使用jsdom测试环境jsdom

// jest.config.js
module.exports = {
  testEnvironment: "jsdom",
};

Otherwise, the WebSocket constructor will be undefined since it is only available on web browser environments and, by default, Jest runs in node environment.否则, WebSocket构造函数将是undefined因为它仅在 Web 浏览器环境中可用,并且默认情况下,Jest 在node环境中运行。

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

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