I try to mock a prop called actionClicked but my test failed, I have a simple component as below
const ButtonAction: React.FC = ({ actionClicked }) => {
const handleClick = (action) => () => actionClicked(action)
return (
<div
data-testid="some-action"
onClick={handleClick('something')}
>
<Icon />
</div>
)
}
this is my test, 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
})
I'm not sure why actionClicked
is not been called.
Expected number of calls: >= 1
Received number of calls: 0
Any thoughts?
This behaviour occurs because userEvent.click
returns a promise.
First you should turn your test to async
and then 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);
});