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

时间:2020-07-22 13:58:11

标签: javascript reactjs react-redux jestjs react-testing-library

我正在测试带有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
})

对于如何使此函数模拟正常工作的任何建议,我将不胜感激。

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

谢谢!

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:-2)

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