How to mock dependency in Jest with TypeScript?

Sometimes, we want to mock dependency in Jest with TypeScript.

In this article, we’ll look at how to mock dependency in Jest with TypeScript.

How to mock dependency in Jest with TypeScript?

To mock dependency in Jest with TypeScript, we can use the jest.mock method.

For instance, we write

import * as dep from "../dependency";
jest.mock("../dependency");

const mockedDependency = <jest.Mock<typeof dep.default>>dep.default;

it("should do what I need", () => {
  mockedDependency.mockReturnValueOnce("return");
});

to call jest.mock to mock the ./dependency module.

We set the type of it with jest.Mock<typeof dep.default>

And we get the its default export with dep.default.

Conclusion

To mock dependency in Jest with TypeScript, we can use the jest.mock method.