How to mock a React.MouseEvent<{}, MouseEvent> onClick event?
Asked Answered
C

1

15

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>?

Courage answered 13/8, 2020 at 21:34 Comment(3)
Were you able to find a solution for this?Badly
Does this answer your question? Simulate a button click in JestEnchiridion
@Royal Rat try this approach https://mcmap.net/q/157538/-simulate-a-button-click-in-jestEnchiridion
E
1

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} />)
})
Eldenelder answered 16/11, 2022 at 16:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.