[英]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.我正在使用 jest/react-testing-library 测试反应组件,无论我尝试什么,我都无法在我的测试中正确模拟函数。 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.
每当我运行调用我试图模拟的组件功能之一的 fireEvent 时,它都会调用原始的 function 而不是我试图模拟的 function。 I've looked through all relevant questions on StackOverflow, but none of the solutions are working for me.
我查看了有关 StackOverflow 的所有相关问题,但没有一个解决方案对我有用。
I've tried using both jest.fn() and jest.spyOn() and neither has worked.我试过同时使用 jest.fn() 和 jest.spyOn() ,但都没有奏效。
My mock (for a function from component 'PasswordResetConfirmation') is as follows:我的模拟(对于来自组件“PasswordResetConfirmation”的 function)如下:
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.对于如何让这个 function 模拟工作的任何建议,我将不胜感激。
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.作为后续行动,我还尝试在这些测试中从不同的文件(不是我当前正在测试的组件)模拟 function,并且在调用原始 function 而不是模拟时遇到了类似的问题。
Thank you!谢谢!
Maybe the code below might be useful for you too.也许下面的代码也可能对您有用。
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);
Try it with enzyme
and enzyme-react-adapter-15
(you have to install both thru npm
)尝试使用
enzyme
和enzyme-react-adapter-15
(您必须通过npm
安装两者)
Then test it like this (and note that your handleOk() can't be an arrow function):然后像这样测试它(并注意你的 handleOk() 不能是箭头函数):
import Enzyme, { mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
it('...', (done) => {
const mockHandleOk = jest.spyOn(PasswordResetConfirmation.prototype, 'handleOk').mockImplementationOnce(() => {});
const wrapper = mount(
<MemoryRouter>
<PasswordResetConfirmation/>
</MemoryRouter>
);
const button = wrapper.find('#reset-confirm-button');
expect(button).toHaveLength(1);
button.simulate('click');
setTimeout(function() {
expect(mockHandleOk).toHaveBeenCalled();
}, 500);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.