How to mock history.push with the new React Router Hooks using Jest?

Sometimes, we want to mock history.push with the new React Router Hooks using Jest.

In this article, we’ll look at how to mock history.push with the new React Router Hooks using Jest.

How to mock history.push with the new React Router Hooks using Jest?

To mock history.push with the new React Router Hooks using Jest, we can call jest.mock to mock the useHistory hook.

For instance, we write

import React from 'react';
import {
  MemoryRouter
} from 'react-router-dom';
import {
  render,
  fireEvent
} from '@testing-library/react';
import RouteNotFound from './NotFound';

const mockHistoryPush = jest.fn();

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useHistory: () => ({
    push: mockHistoryPush,
  }),
}));

describe('RouteNotFound', () => {
  it('Redirects to correct URL on click', () => {
    const {
      getByRole
    } = render(
      <MemoryRouter>
        <RouteNotFound />
      </MemoryRouter>,
    );

    fireEvent.click(getByRole('button'));
    expect(mockHistoryPush).toHaveBeenCalledWith('/help');
  });
});

to call jest.mock with a function that returns an object with the actual members of react-router-dom as returned by requireActual.

And then we set useHistory to a function that returns an object with push set to mockHistoryPush.

Then we can use the mock when we call expect.

Conclusion

To mock history.push with the new React Router Hooks using Jest, we can call jest.mock to mock the useHistory hook.