Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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. However no matter the timeout I assign, it hangs on JestJS. On the browser - Firefox, Edge Chromium it works perfectly fine.

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);
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I refactored your code a little bit and added a WebSocket server using ws NPM package on the test setup:

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.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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda