如何模拟 React.MouseEvent<{}, MouseEvent> onClick 事件?

Roy*_*Rat 15 javascript typescript reactjs jestjs enzyme

我正在使用 Jest 测试用 TypeScript 编写的 React 组件。我无法使用.simulate(),因为它已被弃用,而只支持直接调用组件的onClick()函数 prop。这是我的测试代码:

// 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);
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时,我收到错误:Argument of type 'MouseEvent' is not assignable to parameter of type 'MouseEvent<{}, MouseEvent>'.我的问题是,如何模拟 MouseEvent<{}, MouseEvent> 类型的事件?

tec*_*oke 1

如果您使用 React,官方建议测试是使用 RTL 和 userEvent。这允许您执行以下操作...

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'}))
Run Code Online (Sandbox Code Playgroud)

您可以使用 jest.fn() 模拟您的点击处理程序,如下所示......

const myHandler = jest.fn()
Run Code Online (Sandbox Code Playgroud)

并检查它是用...调用的

expect(myHandler).toHaveBeenCalled()
Run Code Online (Sandbox Code Playgroud)

或者,如果您想检查参数...

expect(myHandler).toHaveBeenCalledWith({some: 'object', or: 'wevs'})
Run Code Online (Sandbox Code Playgroud)

请注意,如果您的代码直接在 useEffect 中进行 Dom 更改,您可能必须将渲染包装在“act()”函数中,该函数也可以从@testing-library/react例如导入

let dom: any
await act(() => {
    dom = render(<MyComponent {...myProps} />)
})
Run Code Online (Sandbox Code Playgroud)