Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda