Intento simular un accesorio llamado actionClicked pero mi prueba falló, tengo un componente simple como el siguiente
const ButtonAction: React.FC = ({ actionClicked }) => { const handleClick = (action) => () => actionClicked(action) return ( <div data-testid="some-action" onClick={handleClick('something')} > <Icon /> </div> ) }
esta es mi prueba, button.spec.tsx
import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import React from 'react' import ButtonAction from './ButtonAction' test('render ButtonAction', () => { const actionClicked = jest.fn() render(<ButtonAction actionClicked={actionClicked} />) userEvent.click(screen.getByTestId('some-action')) expect(actionClicked).toHaveBeenCalled() //failed here })
No estoy seguro de por qué no se ha llamado a actionClicked
.
Expected number of calls: >= 1 Received number of calls: 0
¿Alguna idea?
Este comportamiento se produce porque userEvent.click
devuelve una promesa.
Primero debe convertir su prueba en async
y luego await userEvent.click
:
test("render ButtonAction", async () => { const actionClicked = jest.fn(); render(<ButtonAction actionClicked={actionClicked} />); await userEvent.click(screen.getByTestId("some-action")); expect(actionClicked).toHaveBeenCalledTimes(1); });