Skip to content

tdd — Test-Driven Development

  • Trigger: /tdd or keywords "TDD", "test-driven", "red-green-refactor"
  • Best for: New features, bug fixes, tasks needing integration tests
  • Not for: Pure exploratory coding, one-off scripts, trivial changes with existing coverage

Overview

tdd makes Claude Code strictly follow test-driven development: write a failing test → write minimal code to pass → refactor. Ensures every line has test coverage.

Trigger Conditions

tdd auto-triggers when you:

  • Mention "TDD approach", "test-driven development"
  • Mention "red-green-refactor"
  • Ask for tests before implementation
  • Use the /tdd command

Examples

Example 1: Utility Function

/tdd Implement a deepClone function supporting Date, RegExp, Map, Set

Claude generates tests first:

javascript
describe('deepClone', () => {
  it('should clone primitive values', () => {
    expect(deepClone(42)).toBe(42);
    expect(deepClone('hello')).toBe('hello');
  });

  it('should deep clone nested objects', () => {
    const obj = { a: { b: { c: 1 } } };
    const cloned = deepClone(obj);
    expect(cloned).toEqual(obj);
    expect(cloned.a).not.toBe(obj.a);
  });

  it('should clone Date objects', () => {
    const date = new Date('2026-01-15');
    const cloned = deepClone(date);
    expect(cloned.getTime()).toBe(date.getTime());
    expect(cloned).not.toBe(date);
  });
});

Then implements incrementally, ensuring all tests pass at each step.

Example 2: API Endpoint

/tdd Implement user registration API POST /api/register with email validation and password strength check
  1. Red: Write integration tests — success, duplicate email, weak password, missing fields
  2. Green: Implement route, validation logic, DB operations
  3. Refactor: Extract validation middleware, improve error handling

Example 3: Bug Fix

/tdd Fix floating-point precision issue in order tax calculation

Write a test reproducing the bug → test fails → fix (e.g., switch to decimal library) → test passes.

Example 4: Refactoring Legacy Code

/tdd Refactor calculateDiscount in src/utils/price.ts, add tests first

Example 5: Component Development

/tdd Build an Autocomplete component with keyboard navigation and debounced search

Workflow

  1. Red — Write test first, run to confirm it fails
  2. Green — Write minimal code to pass the test
  3. Refactor — Optimize code structure under test protection

Notes

  • Test behavior, not implementation details
  • Don't add new features during the refactor phase
  • If a scenario is hard to test, the design may need adjustment
  • For existing codebases, write characterization tests first to lock in current behavior
  • Not all code suits TDD — use /prototype for exploratory work first
  • prototype — Prototype first, then implement with TDD
  • review — Review test quality after TDD
  • simplify — Deep simplification during refactor phase