Componente:
const MyComp = ({ handler }) => { return <button onClick={handler}>Test</button> };Prueba:
it('Calls the handler', async () => { const handler = jest.fn(); render(<MyComp handler={handler} />); const button = screen.getByRole('button', { name: /Test/i }); await fireEvent(button, new MouseEvent('click')); expect(handler).toHaveBeenCalled(); });Número esperado de llamadas: >= 1 Número de llamadas recibidas: 0
Intenta usar userEvent.click , así
it('Calls the handler', async () => { const handler = jest.fn(); render(<MyComp handler={handler} />); const button = screen.getByRole('button', { name: /Test/i }); await userEvent.click(button); expect(handler).toHaveBeenCalled(); });Tres opciones:
Haga que el evento burbujee, como se muestra en el ejemplo (no devuelve una promesa, no se necesita await ):
fireEvent(button, new MouseEvent("click", { bubbles: true }));Use el método de conveniencia , que agrega propiedades de eventos predeterminadas, incluido el burbujeo (del mismo modo):
fireEvent.click(button); Use userEvent (devuelve una promesa , a partir de v14):
await userEvent.click(button);