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.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í .
O podrías hacerlo así:
it('calls console.log with "hello"', () => { const consoleSpy = jest.spyOn(console, 'log'); console.log('hello'); expect(consoleSpy).toHaveBeenCalledWith('hello'); });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 }); });