npm install -D typescript
Write unit tests for a UserService using vi.fn() mocks for the repository.
1 export interface User { id: string; name: string; email: string; } 2 3 export interface UserRepo { 4 findById(id: string): Promise<User | null>; 5 save(user: Omit<User, 'id'>): Promise<User>; 6 } 7 8 export class UserService { 9 constructor(private repo: UserRepo) {} 10 11 async getUser(id: string): Promise<User> { 12 const user = await this.repo.findById(id); 13 if (!user) throw new Error(`User ${id} not found`); 14 return user; 15 } 16 17 async createUser(data: { name: string; email: string }): Promise<User> { 18 if (!data.email.includes('@')) throw new Error('Invalid email'); 19 return this.repo.save(data); 20 } 21 }
>3 tests passing: success, not-found, creates-correctly
Sign in to share your feedback and join the discussion.