React测试库jest.fn()tohaveBeencalled()不起作用

发布于 2025-02-12 21:10:47 字数 485 浏览 1 评论 0 原文

组件:

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

Component:

const MyComp = ({ handler }) => {
  return <button onClick={handler}>Test</button>
};

Test:

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();
});

Expected number of calls: >= 1
Received number of calls: 0

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

假扮的天使 2025-02-19 21:10:47

三个选项:

  • 制作事件气泡,如示例(它不返回承诺,不等待):

      fireevent(按钮,new Mouseevent(“单击”,{bubbles:true}));
     
  • 使用便利方法 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 包括冒泡(同样):

      fireevent.click(button);
     
  • 使用 do 返回诺言,从v14开始):

     等待userevent.click(button);
     

Three options:

  • Make the event bubble, as shown in the example (it doesn't return a promise, no await needed):

    fireEvent(button, new MouseEvent("click", { bubbles: true }));
    
  • Use the convenience method, which adds default event properties including bubbling (likewise):

    fireEvent.click(button);
    
  • Use userEvent (does return a promise, as of v14):

    await userEvent.click(button);
    
明明#如月 2025-02-19 21:10:47

尝试使用 userevent.click ,像这样

it('Calls the handler', async () => {
   const handler = jest.fn();
   render(<MyComp handler={handler} />);

   const button = screen.getByRole('button', { name: /Test/i });
   await userEvent.click(button);

   expect(handler).toHaveBeenCalled();
});

Try using userEvent.click, like this

it('Calls the handler', async () => {
   const handler = jest.fn();
   render(<MyComp handler={handler} />);

   const button = screen.getByRole('button', { name: /Test/i });
   await userEvent.click(button);

   expect(handler).toHaveBeenCalled();
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文