Unit Testing
Write unit tests with Jest.
Setup
bash
npm install -D jest ts-jest @types/jestnpx ts-jest config:initjavascript
// jest.config.jsmodule.exports = { preset: 'ts-jest', testEnvironment: 'node', roots: ['<rootDir>/src'], testMatch: ['**/*.spec.ts', '**/*.test.ts'], collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts'],};Testing Pure Functions
typescript
// src/utils/price.tsexport function calculateDiscount(price: number, percentage: number): number { if (price < 0 || percentage < 0 || percentage > 100) { throw new Error('Invalid values'); } return price - (price * percentage / 100);}typescript
// src/utils/price.spec.tsimport { calculateDiscount } from './price'; describe('calculateDiscount', () => { it('should calculate 10% discount', () => { expect(calculateDiscount(100, 10)).toBe(90); }); it('should throw for negative price', () => { expect(() => calculateDiscount(-100, 10)).toThrow('Invalid values'); });});Mocking
typescript
// src/services/product.service.spec.tsimport { ProductService } from './product.service';import { prisma } from '../config/database'; jest.mock('../config/database', () => ({ prisma: { product: { findMany: jest.fn(), findUnique: jest.fn(), create: jest.fn(), }, },})); describe('ProductService', () => { let service: ProductService; beforeEach(() => { service = new ProductService(); jest.clearAllMocks(); }); describe('findAll', () => { it('should return products list', async () => { const mockProducts = [{ id: '1', name: 'Product 1' }]; (prisma.product.findMany as jest.Mock).mockResolvedValue(mockProducts); const result = await service.findAll(); expect(prisma.product.findMany).toHaveBeenCalled(); expect(result).toEqual(mockProducts); }); }); describe('findById', () => { it('should return product by id', async () => { const mockProduct = { id: '1', name: 'Product 1' }; (prisma.product.findUnique as jest.Mock).mockResolvedValue(mockProduct); const result = await service.findById('1'); expect(result).toEqual(mockProduct); }); it('should return null if not found', async () => { (prisma.product.findUnique as jest.Mock).mockResolvedValue(null); const result = await service.findById('999'); expect(result).toBeNull(); }); });});Running Tests
bash
npm testnpm test -- --watchnpm test -- --coverageSummary
- ✅ Jest with TypeScript
- ✅ Testing pure functions
- ✅ Mocking dependencies
- ✅ Code coverage
Next lesson: Integration Testing! 🚀