TypeScript | Testing with TypeScript| Question7

Last Updated :
Discuss
Comments

How would you create a type-safe mock using Jest?

TypeScript
interface UserService {
    getUser: (id: number) => string;
}

const mockUserService: jest.Mocked<UserService> = {
    getUser: jest.fn().mockReturnValue("Pranjal"),
};


Jest does not support type-safe mocking.

Use the jest.Mocked<T> utility for type-safe mocks.

Create mocks by directly implementing the interface.

Mocks do not require adherence to type definitions.

Share your thoughts in the comments