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

291
Views
Pruebas de mecanografiado, React y Socket.io-client

Estoy tratando de descubrir cómo escribir una aplicación Typescript/React que usa socket.io para comunicarse con un servidor y, por lo tanto, con otros clientes. Sin embargo, me gustaría escribir algunas pruebas al hacerlo.

En mi aplicación de muestra tengo:

 import io, { Socket } from 'socket.io-client'; const App = () => { let socket: Socket; const ENDPOINT = 'localhost:5000'; const join = (event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => { event.preventDefault(); socket = io(ENDPOINT); socket.emit('join', { name: 'Paola', room: '1' }, () => {}); }; return ( <div className="join-container"> <button className="join-button" onClick={join} data-testid={'join-button'}> Sign in </button> </div> ); }; export default App;

Y mi prueba se parece a:

 import App from './App'; import { render, screen, fireEvent } from '@testing-library/react'; import 'setimmediate'; describe('Join', () => { let mockEmitter = jest.fn(); beforeEach(() => { jest.mock('socket.io-client', () => { const mockedSocket = { emit: mockEmitter, on: jest.fn((event: string, callback: Function) => {}), }; return jest.fn(() => { return mockedSocket; } ); }); }); afterEach(() => { jest.clearAllMocks(); }); it('joins a chat', () => { // Arrange render(<App />); const btn = screen.getByTestId('join-button'); // Act fireEvent.click(btn); // Assert expect(btn).toBeInTheDocument(); expect(mockEmitter).toHaveBeenCalled(); }); });

Solo quiero asegurarme de que puedo simular socket.io-client para poder verificar que los mensajes se envían al cliente y que (más tarde) reacciona a los mensajes enviados.

Sin embargo, la prueba está fallando y no parece estar usando mi simulacro.

 Error: expect(jest.fn()).toHaveBeenCalled() Expected number of calls: >= 1 Received number of calls: 0
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

En el documento manual-mocks#examples , hay una nota:

Nota: para simular correctamente, Jest necesita jest.mock('moduleName') esté en el mismo ámbito que la instrucción require/import .

Entonces, hay dos soluciones:

app.tsx :

 import React from 'react'; import io, { Socket } from 'socket.io-client'; const App = () => { let socket: Socket; const ENDPOINT = 'localhost:5000'; const join = (event: React.MouseEvent<HTMLButtonElement>) => { event.preventDefault(); socket = io(ENDPOINT); socket.emit('join', { name: 'Paola', room: '1' }, () => {}); }; return ( <div className="join-container"> <button className="join-button" onClick={join} data-testid={'join-button'}> Sign in </button> </div> ); }; export default App;

Opción 1: llame jest.mock e importe el módulo ./app en el alcance del módulo del archivo de prueba.

app.test.tsx :

 import App from './App'; import { render, screen, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import React from 'react'; let mockEmitter = jest.fn(); jest.mock('socket.io-client', () => { return jest.fn(() => ({ emit: mockEmitter, on: jest.fn(), })); }); describe('Join', () => { afterEach(() => { jest.clearAllMocks(); }); it('joins a chat', () => { // Arrange render(<App />); const btn = screen.getByTestId('join-button'); // Act fireEvent.click(btn); // Assert expect(btn).toBeInTheDocument(); expect(mockEmitter).toHaveBeenCalled(); }); });

Opción 2: Ya que llamas a jest.mock en beforeEach hook, require el módulo './app' en el alcance de la función beforeEach hook también.

app.test.tsx :

 import { render, screen, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import React from 'react'; describe('Join', () => { let mockEmitter = jest.fn(); let App; beforeEach(() => { App = require('./app').default; jest.mock('socket.io-client', () => { const mockedSocket = { emit: mockEmitter, on: jest.fn(), }; return jest.fn(() => mockedSocket); }); }); afterEach(() => { jest.clearAllMocks(); }); it('joins a chat', () => { // Arrange render(<App />); const btn = screen.getByTestId('join-button'); // Act fireEvent.click(btn); // Assert expect(btn).toBeInTheDocument(); expect(fakeEmitter).toHaveBeenCalled(); }); });

versión del paquete:

 "jest": "^26.6.3", "ts-jest": "^26.4.4"

jest.config.js :

 module.exports = { preset: 'ts-jest/presets/js-with-ts', testEnvironment: 'jsdom' }
about 4 years ago · Santiago Gelvez 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!