Jest testing patterns — test structure, mocking, async testing, snapshot
99
99%
Does it follow best practices?
Impact
99%
1.26xAverage score across 6 eval scenarios
Passed
No known issues
The backend team has built a NotificationService that sends email alerts when user accounts are flagged for review. The service fetches user details from a UserRepository and dispatches messages through an EmailClient. Both the repository and email client make network calls to external systems.
Quality assurance requires a test suite for this service before it can be merged to the main branch. The tests should cover the happy path (successful notification sent), edge cases (user not found, email delivery failure), and verify that the service interacts correctly with its dependencies.
Write a complete Jest test file at src/notifications/__tests__/notificationService.test.ts.
The test file should test all public methods of NotificationService, covering at least:
Create the following source files as needed to support the tests. You may write minimal implementations.
src/notifications/notificationService.tsimport { UserRepository } from '../users/userRepository';
import { EmailClient } from '../email/emailClient';
export class NotificationService {
constructor(
private readonly userRepo: UserRepository,
private readonly emailClient: EmailClient
) {}
async notifyFlaggedUser(userId: string): Promise<void> {
const user = await this.userRepo.findById(userId);
if (!user) {
throw new Error(`User not found: ${userId}`);
}
await this.emailClient.send({
to: user.email,
subject: 'Account Review Required',
body: `Hello ${user.name}, your account has been flagged for review.`,
});
}
}src/users/userRepository.tsexport interface User {
id: string;
name: string;
email: string;
}
export class UserRepository {
async findById(id: string): Promise<User | null> {
throw new Error('Not implemented');
}
}src/email/emailClient.tsexport interface EmailPayload {
to: string;
subject: string;
body: string;
}
export class EmailClient {
async send(payload: EmailPayload): Promise<void> {
throw new Error('Not implemented');
}
}