簡體   English   中英

JestJS - 多個 websocket 連接掛起 Jest

[英]JestJS - Multiple websocket connections hangs Jest

我正在使用這個函數來測試我的服務器,它創建了盡可能多的 websocket 連接並檢查我的游戲何時開始。 但是,無論我分配的超時時間如何,它都會掛在 JestJS 上。 在瀏覽器 - 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()
            }
        }
    });
}

有誰知道它為什么會發生,我可以做些什么來確保它不再發生。

測試代碼;

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

我稍微重構了你的代碼,並在測試設置中使用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.

這僅在 Jest 還配置為使用jsdom測試環境jsdom

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

否則, WebSocket構造函數將是undefined因為它僅在 Web 瀏覽器環境中可用,並且默認情況下,Jest 在node環境中運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM