首页 > 解决方案 > 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!

标签: javascriptreactjsreact-reduxjestjsreact-testing-library

解决方案


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

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


推荐阅读