Back to the academy

What TDD is and how to master the Red-Green-Refactor cycle

Why tests are the primary documentation of software, the Red → Green → Refactor cycle step by step in TypeScript/Vitest, and how to reach 100% logic coverage in seconds.

Fundamental · TypeScript · Vitest · Testing Library

Why tests are the real documentation of software

A README goes stale as soon as the next PR is merged; a test that describes a behaviour fails as soon as that behaviour stops being true. That is why, in Elevation, every business rule —cost by specific lot, the 300-line limit, the minimum contrast— lives in a test whose name reads like a sentence. Newcomers read the `describe` and `it` blocks and understand what the system does without opening the production code.

❌ Antipattern

it('test 1', () => {
  const r = calc([10, 20], 5);
  expect(r).toBeTruthy();
});

✅ Stoic pattern

describe('applyDiscount', () => {
  it('takes 10% off orders above 100 EUR', () => {
    expect(applyDiscount(120)).toBe(108);
  });

  it('leaves smaller orders untouched', () => {
    expect(applyDiscount(80)).toBe(80);
  });
});

Key takeaways

  • The test name is the specification: it must read like a business rule.
  • A test is documentation that warns you by itself when it goes stale.
  • A vague assertion such as `toBeTruthy()` documents nothing: assert the exact value.

Anatomy of the Red → Green → Refactor cycle

Red: you write the smallest test that expresses the next behaviour and watch it fail for the right reason. Green: you write the least code that makes it pass, even if it is naive. Refactor: with the green suite as a safety net, you remove duplication and improve names without changing the behaviour. Cycles last minutes, not hours: if you have been red for twenty minutes, the step was too big. With `vitest --watch`, every save re-runs the affected tests.

❌ Antipattern

// 300 lines written first, tests "later"
export function applyDiscount(total: number, user?: User, coupon?: string) {
  if (coupon) { /* ... */ }
  if (user?.vip) { /* ... */ }
  return total > 100 ? total * 0.9 : total;
}

✅ Stoic pattern

// 1. RED: one behaviour, seen failing
it('takes 10% off orders above 100 EUR', () => {
  expect(applyDiscount(120)).toBe(108);
});

// 2. GREEN: the least code that passes
export const applyDiscount = (total: number) => (total > 100 ? total * 0.9 : total);

// 3. REFACTOR: name the rule, the suite stays green
const DISCOUNT_THRESHOLD = 100;
const DISCOUNT_RATE = 0.1;

Key takeaways

  • Seeing the test red proves it can fail; a test that never failed protects nothing.
  • On green, the bare minimum: generalisation comes with the next test, not before.
  • Refactor only on green, in steps that keep the suite green.

Hybrid strategy: strict TDD vs. Spec-First + Regression Locks

Not all code deserves the same ritual. Algorithms with exact inputs and outputs —financial calculations, dates, parsers, currency conversion— are written with strict TDD: the test comes first because the right result is known in advance. React interfaces are better explored live: first you pin down the specification (loading, error and empty states, interactions and `data-testid`), then you prototype and, as soon as it works, you lock the behaviour with regression tests so no later iteration can break it.

Key takeaways

  • Strict TDD wherever the exact result is known before coding: money, dates, parsers.
  • In the UI: specification first, prototype next, and an immediate lock with regression tests.
  • The shared rule: no new behaviour reaches production without a test that certifies it.

Pure libraries (*Presenter.ts): 100% coverage in under 3 seconds

If the calculation lives inside the component, every test has to mount React, fake the context and wait for renders. Moved into a pure function in a `*Presenter.ts`, the same calculation is tested with one call and one `expect`: hundreds of cases in milliseconds. The component becomes a thin layer that only renders what the presenter returns, and the logic reaches 100% coverage without the suite taking more than a few seconds.

❌ Antipattern

function PnlBadge({ order, price }: Props) {
  const sign = order.side === 'SHORT' ? -1 : 1;
  const pnl = ((price - order.entry) / order.entry) * 100 * sign;
  return <span>{pnl.toFixed(2)}%</span>;
}

✅ Stoic pattern

// pnlPresenter.ts: pure, no React
export function pnlPct(entry: number, price: number, side: Side): number {
  const raw = ((price - entry) / entry) * 100;
  return side === 'SHORT' ? -raw : raw;
}

// pnlPresenter.test.ts: milliseconds, no render
it('inverts the sign for shorts', () => {
  expect(pnlPct(100, 90, 'SHORT')).toBe(10);
});

Key takeaways

  • Logic that does not import React is tested without React: fast and never flaky.
  • The component becomes a thin, declarative layer that barely needs tests.
  • A pure presenter is reusable: the same calculation serves the UI, the SEO snapshot or another module.