Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
JestJS - Múltiples conexiones websocket cuelgan Jest

Estoy usando esta función para probar mi servidor que crea la mayor cantidad de conexiones websocket y verifica cuándo comienza mi juego. Sin embargo, no importa el tiempo de espera que asigne, se cuelga en JestJS. En el navegador - Firefox, Edge Chromium funciona perfectamente bien.

 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() } } }); }

¿Alguien sabe por qué sucede qué puedo hacer para asegurarme de que no vuelva a suceder?

código de prueba;

 test('Check the game starts', () => { return expect(checkGameStart(4)).resolves.toBe(true); });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Refactoricé un poco su código y agregué un servidor WebSocket usando el paquete ws NPM en la configuración de prueba:

 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.

Esto solo funciona si Jest también está configurado para usar un entorno de prueba jsdom :

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

De lo contrario, el constructor de WebSocket no estará undefined , ya que solo está disponible en entornos de navegador web y, de forma predeterminada, Jest se ejecuta en un entorno de node .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!