Skip to contentPedro Farbo
Lesson 17 / 2555 min

Unit Testing

Unit Testing

Write unit tests with Jest.

Setup

bash
npm install -D jest ts-jest @types/jestnpx ts-jest config:init
javascript
// 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 -- --coverage

Summary

  • ✅ Jest with TypeScript
  • ✅ Testing pure functions
  • ✅ Mocking dependencies
  • ✅ Code coverage

Next lesson: Integration Testing! 🚀

Enjoyed the content? Your contribution helps keep everything online and free!

PIX:0737160d-e98f-4a65-8392-5dba70e7ff3e