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