Skip to content

ReactJS

alex [dot] kramer [at] g_m_a_i_l [dot] com edited this page Dec 3, 2021 · 8 revisions

Jest

Mock React Router useHistory

import React from "react";
import { MemoryRouter, useHistory } from 'react-router-dom';
import { render } from "@testing-library/react";

const HistoryTest = ({goto}) => {
  const history = useHistory();
  history.push(goto);
  return <></>
}

const mockHistoryPush = jest.fn();

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

describe('Test mocking useHistory', () => {
  it('Redirects to correct URL on click', () => {
    render(
      <MemoryRouter>
        <HistoryTest goto="lol" />
      </MemoryRouter>,
    );

    expect(mockHistoryPush).toHaveBeenCalledWith('lol');
  });
});

Clone this wiki locally