Categories
React Answers

How to mock the useHistory hook in Jest?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to mock the useHistory hook in Jest?”

Leave a Reply

Your email address will not be published. Required fields are marked *