Philip Feldmann
Philip Feldmann

Reputation: 8375

How to reuse jest mock of react-router's useHistory

I am mocking the useHistory of react-router-dom in my test like this:

jest.mock("react-router-dom", () => ({
  useHistory: () => ({
    length: 13,
    push: jest.fn(),
    block: jest.fn(),
    createHref: jest.fn(),
    go: jest.fn(),
    goBack: jest.fn(),
    goForward: jest.fn(),
    liten: jest.fn(),
    replace: jest.fn(),
    action: "REPLACE",
    location: null
  })
}));

This works perfectly fine in a single test, but I need this for basically every single test and I don't want to copy it every single time.

How can I reuse this mock? I've tried the obvious, moving it to a different file and exporting a function that creates the mock:

export default () => jest.mock("react-router-dom", () => ({...})

However, importing it and calling the function to create the mock results in an error.

import useHistoryMock from "../../../testUtils/hooks/useHistory";
useHistoryMock()

My component implementation then throws TypeError: Cannot read property 'history' of undefined, which it doesn't if I define the mock in the test file itself.

What is a convenient way to reuse the mock? I am using typescript so preferably I would not want to break any compiler rules.

Upvotes: 5

Views: 4163

Answers (1)

Safi Nettah
Safi Nettah

Reputation: 1170

You can try with the __mocks__ folder https://jestjs.io/docs/en/manual-mocks.html

Upvotes: 3

Related Questions