Day 1 of 5

Unit Testing with Jest

Unit tests verify individual functions in isolation. Jest is the most popular JavaScript test runner. Today you will write pure unit tests, use matchers, mock dependencies, and run tests in watch mode.

bash
npm install --save-dev jest
# or for TypeScript:
npm install --save-dev jest @types/jest ts-jest
javascript
// src/utils/math.js
export function add(a, b) { return a + b; }
export function divide(a, b) {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}

// src/utils/math.test.js
import { add, divide } from './math';

describe('math utils', () => {
  test('adds two numbers', () => {
    expect(add(2, 3)).toBe(5);
  });

  test('divides two numbers', () => {
    expect(divide(10, 2)).toBe(5);
    expect(divide(10, 2)).toBeCloseTo(5);
  });

  test('throws on divide by zero', () => {
    expect(() => divide(10, 0)).toThrow('Division by zero');
  });
});
javascript
// Mocking modules
import * as api from './api';

jest.mock('./api');

test('calls the API once', async () => {
  api.fetchUser.mockResolvedValue({ id: 1, name: 'Bo' });

  const user = await api.fetchUser(1);

  expect(api.fetchUser).toHaveBeenCalledTimes(1);
  expect(api.fetchUser).toHaveBeenCalledWith(1);
  expect(user.name).toBe('Bo');
});

Exercise: Write 10 Unit Tests

  1. Create a string utils module (capitalize, truncate, slugify)
  2. Write one test for each function
  3. Add an edge case test (empty string, null input)
  4. Run jest --watch and fix failures in real time
  5. Check coverage with jest --coverage

Day 1 Summary

Finished this lesson?