Reputation: 165
I am using Jest to test a React component written in TypeScript. I can't use .simulate()
because that is being deprecated in favor of just directly calling the component's onClick()
function prop. Here is my test code:
// Get the onClick function
const buttonOnClick = wrapper.find('#diffpicker-button').first().props().onClick;
// Make sure the function is not undefined
if (!buttonOnClick) return;
// Mock event
const clickEvent = new MouseEvent('click');
Object.assign(clickEvent, { preventDefault: jest.fn() });
// Call the onClick function
buttonOnClick(clickEvent);
However, when I do this I get the error: Argument of type 'MouseEvent' is not assignable to parameter of type 'MouseEvent<{}, MouseEvent>'.
My question is, how do I mock an event of type MouseEvent<{}, MouseEvent>?
Upvotes: 15
Views: 5316
Reputation: 3535
If you're using React the official recommendation for testing is to use RTL and userEvent. That allows you to do the following...
import {render} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
const dom = render(<MyComponent {...myProps} />)
await userEvent.click(dom.getByRole('button', {name: 'Go'}))
You can mock your click handler with jest.fn() like so...
const myHandler = jest.fn()
And check it was called with...
expect(myHandler).toHaveBeenCalled()
Or, if you want to check the args...
expect(myHandler).toHaveBeenCalledWith({some: 'object', or: 'wevs'})
Note that if you're code makes Dom changes in a useEffect straight out of the gate you may have to wrap your render in the 'act()' function which can also be imported from @testing-library/react
e.g.
let dom: any
await act(() => {
dom = render(<MyComponent {...myProps} />)
})
Upvotes: 1