【发布时间】:2022-01-20 19:32:42
【问题描述】:
我正在尝试验证位于反应函数 useEffect 挂钩内的自定义事件侦听器,如下所示:
export interface specialEvent extends Event {
detail?: string
}
function Example() {
React.useEffect(()=>{
document.addEventListener('specialEvent', handleChange)
return () => {
document.removeEventListener('specialEvent',handleChange)
}
})
const handleChange = (event:SpecialEvent) => {
...
}
}
我想触发这个自定义事件监听器并开玩笑地测试它:
it('should trigger "specialEvent" event Listener Properly', async () => {
const specialEvent = new CustomEvent('specialEvent')
const handleChange = jest.fn()
render(<Example />)
await waitFor(() => {
window.document.dispatchEvent(specialEvent)
expect(window.document.dispatchEvent).toHaveBeenNthCalledWith(1, 'specialEvent')
expect(specialEvent).toHaveBeenCalledTimes(1)
})
})
这段代码给了我以下错误:
expect(received).toHaveBeenNthCalledWith(n, ...expected)
Matcher error: received value must be a mock or spy function
Received has type: function
Received has value: [Function dispatchEvent]
按照其中一个答案的建议,我尝试了这个:
//Assert Statements
const specialEvent = new CustomEvent('specialEvent');
const handleSelect = jest.fn();
act(() => {
render(<Example />)
});
await waitFor(() => {
window.document.dispatchEvent(specialEvent)
expect(handleSelect).toHaveBeenCalledTimes(1)
});
但这一次它说预期的呼叫是 1 但收到的是 0。
谁能帮我解决这个问题?
【问题讨论】:
标签: reactjs typescript jestjs react-testing-library ts-jest