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

1.7K
Vistas
¿Cómo pruebo un jest console.log?

Estoy usando create-react-app e intento escribir una prueba de broma que verifique el resultado de un console.log .

Mi función para probar es:

 export const log = logMsg => console.log(logMsg);

mi prueba es:

 it('console.log the text "hello"', () => { console.log = jest.fn('hello'); expect(logMsg).toBe('hello'); });

Aquí está mi error

 FAIL src/utils/general.test.js ● console.log the text hello expect(received).toBe(expected) Expected value to be (using ===): "hello" Received: undefined Difference: Comparing two different types of values. Expected string but received undefined.
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Si desea verificar que console.log recibió el parámetro correcto (el que pasó), debe verificar la mock de su jest.fn() .
También debe invocar su función de log ; de lo contrario, console.log nunca se invoca:

 it('console.log the text "hello"', () => { console.log = jest.fn(); log('hello'); // The first argument of the first call to the function was 'hello' expect(console.log.mock.calls[0][0]).toBe('hello'); });

o

 it('console.log the text "hello"', () => { console.log = jest.fn(); log('hello'); // The first argument of the first call to the function was 'hello' expect(console.log).toHaveBeenCalledWith('hello'); });

Si opta por este enfoque, no olvide restaurar el valor original de console.log .

Otra opción es usar jest.spyOn (en lugar de reemplazar console.log , creará un proxy para él):

 it('console.log the text "hello"', () => { const logSpy = jest.spyOn(console, 'log'); console.log('hello'); expect(logSpy).toHaveBeenCalledWith('hello'); });

Lea más aquí .

over 4 years ago · Santiago Trujillo Denunciar

0

O podrías hacerlo así:

 it('calls console.log with "hello"', () => { const consoleSpy = jest.spyOn(console, 'log'); console.log('hello'); expect(consoleSpy).toHaveBeenCalledWith('hello'); });
over 4 years ago · Santiago Trujillo Denunciar

0

Otra opción es guardar una referencia al registro original, reemplazar con un simulacro de broma para cada prueba y restaurar después de que todas las pruebas hayan terminado. Esto tiene un ligero beneficio para no contaminar la salida de la prueba y aún poder usar el método de registro original para fines de depuración.

 describe("Some behavior that will log", () => { const log = console.log; // save original console.log function beforeEach(() => { console.log = jest.fn(); // create a new mock function for each test }); afterAll(() => { console.log = log; // restore original console.log after all tests }); test("no log", () => { // TODO: test something that should not log expect(console.log).not.toHaveBeenCalled(); }); test("some log", () => { // TODO: execute something that should log expect(console.log).toHaveBeenCalledWith( expect.stringContaining("something") ); const message = console.log.mock.calls[0][0]; // get actual log message log(message); // actually log out what the mock was called with }); });
over 4 years ago · Santiago Trujillo 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