我正在使用Jest测试用TypeScript编写的React组件。我不能使用.simulate(),因为人们反对直接调用组件的onClick()函数支柱。这是我的测试代码:
// 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);但是,当我这样做时,我得到了一个错误:Argument of type 'MouseEvent' is not assignable to parameter of type 'MouseEvent<{}, MouseEvent>'.我的问题是,如何模拟MouseEvent<{},MouseEvent>类型的事件?
发布于 2022-11-16 16:03:11
如果您正在使用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'}))您可以使用jest.fn()来模拟单击处理程序,如下所示..。
const myHandler = jest.fn()检查它是用..。
expect(myHandler).toHaveBeenCalled()或者,如果你想检查args..。
expect(myHandler).toHaveBeenCalledWith({some: 'object', or: 'wevs'})请注意,如果您的代码使Dom更改在useEffect中直接走出大门,您可能必须将您的呈现包装在'act()‘函数中,这个函数也可以从@testing-library/react导入。
let dom: any
await act(() => {
dom = render(<MyComponent {...myProps} />)
})https://stackoverflow.com/questions/63403525
复制相似问题