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 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.

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 *