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

1.7K
Views
¿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 answers
Answer question

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 Report

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 Report

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