javascript - How to mock functions for testing using the React Testing Library + Jest
问题描述
I'm testing react components with jest/react-testing-library, and no matter what I try I am unable to mock functions correctly in my tests. Whenever I run a fireEvent that calls one of the component's functions I'm trying to mock, it calls the original function rather than the function I'm trying to mock. I've looked through all relevant questions on StackOverflow, but none of the solutions are working for me.
I've tried using both jest.fn() and jest.spyOn() and neither has worked.
My mock (for a function from component 'PasswordResetConfirmation') is as follows:
PasswordResetConfirmation.handleOkay = jest.fn(() => true)
test('handleOkay method is called when user clicks Okay button', () => {
const {getByTestId} = render(<MemoryRouter><PasswordResetConfirmation/> </MemoryRouter>)
let button = getByTestId('reset-confirm-button')
expect(button).toBeInTheDocument();
fireEvent.click(button) // this is where the mocked handleOkay method should be called but isn't
})
I would greatly appreciate any advice about how to get this function mock working.
As a follow-up, I am also trying to mock a function from a different file (not from the component I'm currently testing) in these tests and I'm having similar issues with the original function being called instead of the mock.
Thank you!
解决方案
也许下面的代码也可能对您有用。
const mockFn = jest.fn(() => true);
const { getByTestId } = render(
<Provider store={store}>
<RandomMeals/>
</Provider>
);
const button = getByTestId("random-meals-button-test");
fireEvent.click(button);
expect(mockFn()).toBe(true);
推荐阅读
- html - 有没有办法在播放后立即隐藏 HTML5 视频?
- android-studio - Webview:实施 shouldOverrideUrlLoading 后后退按钮不起作用
- angular - Transloco - 如何为翻译 API 添加范围?
- api - 您是否有关于事件数据响应的数据字典?
- java - Google 结算库 - 处理购买 - 验证购买和授予权利
- php - 检查时隐藏 PHP 和 apache 版本
- windows - 将证书的文件类型从 .txt 转换为 .pem
- string - “时间戳”类型不是“字符串”类型的子类型
- sql - 如何链接到关系数据库 - Visual Basic
- c# - 从 codedom 生成的 dll 触发事件 - 如何从主 exe 应用程序中加入运行时生成的 dll 的事件