How to mock the useHistory hook in Jest?

Sometimes, we want to mock the useHistory hook in Jest.

In this article, we’ll look at how to mock the useHistory hook in Jest.

How to mock the useHistory hook in Jest?

To mock the useHistory hook in Jest, we can call jest.mock with a function to return the return value of useHistory.

For instance, we write

jest.mock("react-router-dom", () => ({
  useHistory: () => ({
    push: jest.fn(),
  }),
}));

to call jest.mock to mock the react-router-dom module and a callback.

In the callback, we return an object that has the useHistory property set to a function that returns the object we want.

We mock the push method by setting it to jest.fn.

Conclusion

To mock the useHistory hook in Jest, we can call jest.mock with a function to return the return value of useHistory.