Categories
TypeScript Answers

How to mock dependency in Jest with TypeScript?

Spread the love

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 set the type of the mocked dependency to jest.Mock<typeof dep.default>.

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 get the cast the type of dep.default to jest.Mock<typeof dep.default>.

Then we can call mockReturnValueOnce without TypeScript compiler errors.

Conclusion

To mock dependency in Jest with TypeScript, we set the type of the mocked dependency to jest.Mock<typeof dep.default>.

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 *