【发布时间】:2020-07-23 04:55:48
【问题描述】:
我正在使用 jest/react-testing-library 测试反应组件,无论我尝试什么,我都无法在我的测试中正确地模拟函数。每当我运行一个调用我试图模拟的组件函数之一的 fireEvent 时,它都会调用原始函数而不是我试图模拟的函数。我查看了 StackOverflow 上的所有相关问题,但没有一个解决方案适合我。
我尝试过同时使用 jest.fn() 和 jest.spyOn() 都没有成功。
我的模拟(对于来自组件“PasswordResetConfirmation”的函数)如下:
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
})
我将不胜感激有关如何让这个函数模拟工作的任何建议。
作为后续行动,我还尝试在这些测试中模拟来自不同文件(而不是来自我当前正在测试的组件)的函数,并且在调用原始函数而不是模拟。
谢谢!
【问题讨论】:
-
不熟悉你正在使用的一些东西,但你可以试试 button.simulate('click') 吗?
-
@TalmacelMarianSilviu 可用于酶但不能用于测试库
-
根据库的开发人员的说法,这是故意以模拟组件方法很难testing-library.com/docs/dom-testing-library/faq的方式完成的。
标签: javascript reactjs react-redux jestjs react-testing-library