如何使用React testing Library+Jest模拟函数进行测试



我正在使用jest/areact测试库测试react组件,无论我尝试什么,我都无法在测试中正确模拟函数。每当我运行一个fireEvent,它调用我试图模拟的组件函数之一时,它就会调用原始函数,而不是我想要模拟的函数。我已经查看了StackOverflow上的所有相关问题,但没有一个解决方案对我有效

我试过同时使用jest.fn((和jest.spyOn((,但都不起作用。

我的mock(针对组件"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
})

我将非常感谢任何关于如何让这个函数模拟工作的建议。

作为后续工作,我还在这些测试中尝试模拟来自不同文件(而不是来自我当前测试的组件(的函数,并且我在调用原始函数而不是模拟时遇到了类似的问题。

谢谢!

也许下面的代码也对您有用。

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

尝试使用enzymeenzyme-react-adapter-15(必须通过npm安装两者(

然后这样测试它(注意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);
}

最新更新