React测试库jest.fn()tohaveBeencalled()不起作用
组件:
const MyComp = ({ handler }) => {
return <button onClick={handler}>Test</button>
};
测试:
it('Calls the handler', async () => {
const handler = jest.fn();
render(<MyComp handler={handler} />);
const button = screen.getByRole('button', { name: /Test/i });
await fireEvent(button, new MouseEvent('click'));
expect(handler).toHaveBeenCalled();
});
预期通话数:&gt; = 1 收到的电话数量:0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
三个选项:
制作事件气泡,如示例(它不返回承诺,不
等待
):使用便利方法 href =“ https://github.com/testing-library/dom-testing-library/blob/54bfa48a5417a417a4cb588888b24dec2685eaa3436fa69/src/src/event-map/event-map.-map.js#l80-l80-l83-proportial a a proportial a a a proportial a proporties a proport 包括冒泡(同样):
使用 do 返回诺言,从v14开始):
Three options:
Make the event bubble, as shown in the example (it doesn't return a promise, no
await
needed):Use the convenience method, which adds default event properties including bubbling (likewise):
Use
userEvent
(does return a promise, as of v14):尝试使用
userevent.click
,像这样Try using
userEvent.click
, like this