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.
And we set mockedDependency to dep.default with type <jest.Mock<typeof dep.default>>.
typeof dep.default sets the data type of mockedDependency to the type of the ../dependency module automatically.
Then we call mockedDependency.mockReturnValueOnce to mock the return value of mockedDependency.
Conclusion
To mock dependency in Jest with TypeScript, we can use the jest.mock method.