0
votes

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!

2
not familiar with some of the stuff you are using but can you try button.simulate('click') instead?Talmacel Marian Silviu
@TalmacelMarianSilviu that works with enzyme but not testing librarySecond Son
According to the devs of the library, it is intentionally done in a way that mocking component methods is hard testing-library.com/docs/dom-testing-library/faq.Second Son

2 Answers

0
votes

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

Try it with enzyme and enzyme-react-adapter-15 (you have to install both thru npm)

Then test it like this (and note that your handleOk() can't be an arrow function):

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