繁体   English   中英

反应测试库 jest.fn() toHaveBeenCalled() 不工作

[英]React Testing Library jest.fn() toHaveBeenCalled() not working

零件:

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

预期来电数:>= 1 已接来电数:0

尝试使用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();
});

三个选项:

  • 使事件冒泡,如示例所示(它不返回承诺,不需要await ):

     fireEvent(button, new MouseEvent("click", { bubbles: true }));
  • 使用便捷方法,它添加了包括冒泡在内的默认事件属性(同样):

     fireEvent.click(button);
  • 使用userEvent确实返回一个承诺,从 v14 开始):

     await userEvent.click(button);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM