Skip to main content

Unit testing

Overview

Unit tests exercise small pieces of code—usually a single function or class—in isolation, using mocks or stubs for collaborators. Fast, deterministic unit suites are the foundation of refactoring confidence and short feedback loops in CI.

Key concepts

  • AAA pattern — Arrange, Act, Assert.
  • Isolation — Control time, I/O, and randomness; avoid flakiness.
  • Test doubles — Mocks, fakes, stubs, spies (terminology varies by framework).
  • Coverage — Line/branch coverage is a signal, not a goal.
  • Naming — Tests document expected behavior for future readers.

Unit test flow

Sample: Jest-style test

import { sum } from './math';

describe('sum', () => {
it('adds two numbers', () => {
expect(sum(2, 3)).toBe(5);
});
});

References