Categories
TypeScript Answers

How to mock the useHistory hook in Jest and TypeScript?

Spread the love

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

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

How to mock the useHistory hook in Jest and TypeScript?

To mock the useHistory hook in Jest and TypeScript, we can mock the react-router-dom module.

For instance, we write

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

in our test file to call jest.mock with the module name and a function that returns the mocked module contents.

In the object returned, we add the useHistory property and set it to a function that returns an object that has the push function set to a mock function returned by jest.fn.

Conclusion

To mock the useHistory hook in Jest and TypeScript, we can mock the react-router-dom module.

By John Au-Yeung

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

Leave a Reply

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