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 e-commerce platform has an inventory management API built with Express. The /api/products endpoint supports listing all products and creating new ones. It delegates all database operations to a ProductRepository class that communicates with a PostgreSQL database.
Before the upcoming product launch, the team needs a test suite for the API layer that can run in CI without a real database. The tests should validate correct request handling, proper response formats, and graceful error handling when the database is unavailable or returns unexpected results.
Write a complete Jest test file at src/api/__tests__/products.test.ts.
Tests should cover at minimum:
src/api/productsRouter.tsimport { Router, Request, Response } from 'express';
import { ProductRepository } from '../db/productRepository';
const router = Router();
const repo = new ProductRepository();
router.get('/products', async (req: Request, res: Response) => {
try {
const products = await repo.findAll();
res.status(200).json({ data: products });
} catch (err) {
res.status(500).json({ error: 'Internal server error' });
}
});
router.post('/products', async (req: Request, res: Response) => {
const { name, price, stock } = req.body;
if (!name || price === undefined || stock === undefined) {
return res.status(400).json({ error: 'name, price, and stock are required' });
}
try {
const product = await repo.create({ name, price, stock });
res.status(201).json({ data: product });
} catch (err) {
res.status(500).json({ error: 'Internal server error' });
}
});
export default router;src/app.tsimport express from 'express';
import productsRouter from './api/productsRouter';
export const app = express();
app.use(express.json());
app.use('/api', productsRouter);src/db/productRepository.tsexport interface Product {
id: number;
name: string;
price: number;
stock: number;
}
export class ProductRepository {
async findAll(): Promise<Product[]> {
throw new Error('Not implemented');
}
async create(data: Omit<Product, 'id'>): Promise<Product> {
throw new Error('Not implemented');
}
}