Hay 3 archivos:
Archivo 1: ayudantes.js
export const helpers = () => ({ bar: () => 'Bar was called', });Archivo 2: TestComponent.js
import React from 'react'; import { helpers } from './helpers'; const TestComponent = () => { const { bar } = helpers(); return ( <><button onClick={bar}/></> ); }; export default TestComponent;Archivo 3: TestComponent.test.js
import React from 'react'; import userEvent from '@testing-library/user-event'; import { screen, render } from '@testing-library/react'; import TestComponent from './TestComponent'; import { helpers } from './helpers'; jest.mock('./helpers', () => ({ helpers: jest.fn(), })); test('bar is called', () => { helpers.mockImplementation(() => ({ bar: jest.fn(), })); render( <TestComponent />, ); userEvent.click(screen.getByRole('button')); expect(???????).toHaveBeenCalled(); });Esta línea es la clave:
expect(???????).toHaveBeenCalled(); La pregunta : ¿Cómo puedo probar si se llamó a la función de bar ? Esperaba que algo similar a expect(helpers().bar) funcionara. Pero no es así.
guarde la función en una variable y utilícela a la espera
test('bar is called', () => { const bar = jest.fn() helpers.mockImplementation(() => ({bar})); render( <TestComponent />, ); userEvent.click(screen.getByRole('button')); expect(bar).toHaveBeenCalled(); });