How to properly mock a repository in unit tests with Jest and TypeScript?
I'm working on a personal project and This might be a silly question, but I'm trying to write unit tests for a service that relies on a repository, but I'm running into issues with mocking the repository methods... My service is written in TypeScript and uses Jest for testing. Here's a simplified version of my service and repository: ```typescript // user.repository.ts export class UserRepository { async findById(id: string): Promise<User | null> { // Simulating a database call return await db.findUserById(id); } } // user.service.ts import { UserRepository } from './user.repository'; export class UserService { constructor(private userRepository: UserRepository) {} async getUserById(id: string): Promise<User | null> { return await this.userRepository.findById(id); } } ``` I've set up my Jest test like this: ```typescript // user.service.spec.ts import { UserService } from './user.service'; import { UserRepository } from './user.repository'; describe('UserService', () => { let userService: UserService; let userRepository: jest.Mocked<UserRepository>; beforeEach(() => { userRepository = { findById: jest.fn() } as any; userService = new UserService(userRepository); }); it('should return null if user is not found', async () => { userRepository.findById.mockResolvedValue(null); const result = await userService.getUserById('non-existing-id'); expect(result).toBeNull(); }); }); ``` However, I'm getting the following behavior when I run the tests: ``` TypeError: userRepository.findById is not a function ``` I checked that `jest.fn()` is properly creating a mock function, but it seems like it's not being recognized correctly. I also tried explicitly defining the type for `userRepository`, but that didn't change anything. Does anyone know why this might be happening? Are there best practices for mocking classes in Jest with TypeScript that I might be missing? Also, if you could point out any potential pitfalls in this setup, that would be greatly appreciated! I'm working on a application that needs to handle this. This is part of a larger service I'm building. What's the best practice here? I've been using Typescript for about a year now. This is happening in both development and production on macOS. I appreciate any insights!