Test-Driven Development writes tests before writing the code they test. The cycle: Red (write a failing test) → Green (write minimal code to pass) → Refactor (clean up while keeping tests green). TDD produces well-tested, modular code and catches bugs before they reach production.

How TDD Works

TDD cycle: 1) Write test: expect(add(2, 3)).toBe(5). 2) Run test — it fails (red). 3) Write code: function add(a, b) { return a + b; }. 4) Run test — it passes (green). 5) Refactor if needed. 6) Write the next test. Each cycle takes minutes, and you always have working, tested code.

Key Concepts

  • Red-Green-Refactor — The TDD cycle — fail, pass, clean up — repeated for each small behavior
  • Test First — Writing the test before the code forces you to think about the interface and behavior first
  • Small Steps — Each test adds one small behavior — the code evolves incrementally
  • Refactoring Safety — Tests give you confidence to restructure code — if tests pass, the behavior is preserved

Frequently Asked Questions

Is TDD worth the extra time?

TDD often saves time overall — bugs are caught immediately, design is cleaner, and refactoring is safe. It's slower for throwaway code and prototypes.

Do teams actually use TDD?

Some do, many don't strictly. Writing tests (even test-after) is more common than strict TDD. The principles — small increments, tests as documentation, refactoring confidence — are valuable regardless.