Test-driven development (TDD) reverses the usual order: you write a failing test first, then just enough code to pass it, then improve the code while the tests keep you safe. It sounds like a small change in sequence, but it changes what you build: code written to satisfy a test is testable by construction, and the tests document the behavior you intended rather than the behavior you happened to write. This lesson walks through real red-green-refactor cycles with Vitest, explains when TDD helps and when it doesn't, and covers the habits that keep a growing test suite maintainable.
Before you start
You should be comfortable writing Vitest tests and test doubles from the earlier lessons, especially Unit Testing in Real Applications: Mocks, Stubs, Fixtures, and Code Coverage. All output in this lesson is real, from Vitest 5.
The cycle: red, green, refactor
TDD, as described by Kent Beck, repeats a short loop:
- Red: write a small test for the next bit of behavior, and run it. It must fail, and fail for the reason you expect.
- Green: write the simplest code that makes it pass. Not the final design; just enough.
- Refactor: improve the code (and the tests) without changing behavior, running the tests after each change.
Each loop takes minutes. The failing test is essential: it proves the test can detect the missing behavior. A test that has never failed might not be testing anything.
A worked example: formatting durations
The cooking school's class pages need to show durations: 45 minutes as "45 min," 90 minutes as "1 h 30 min," and 120 minutes as "2 h."
Cycle 1
Red. Start with the simplest case:
import { describe, expect, it } from "vitest";
import { formatDuration } from "./duration";
describe("formatDuration", () => {
it("shows minutes under an hour", () => {
expect(formatDuration(45)).toBe("45 min");
});
});With only a placeholder function (throw new Error("Not implemented")), the test fails for the expected reason:
× shows minutes under an hour 3ms
Error: Not implemented
Tests 1 failed (1)Green. The simplest code that passes:
export function formatDuration(minutes: number): string {
return `${minutes} min`;
} Tests 1 passed (1)It feels too simple, and that's the point. The next test will force the real logic, and you'll only write logic a test demands.
Cycle 2
Red. Add the hour cases:
it("shows hours and minutes from an hour up", () => {
expect(formatDuration(90)).toBe("1 h 30 min");
});
it("leaves out zero minutes", () => {
expect(formatDuration(120)).toBe("2 h");
}); × shows hours and minutes from an hour up 4ms
× leaves out zero minutes 1ms
AssertionError: expected '90 min' to be '1 h 30 min' // Object.is equality
AssertionError: expected '120 min' to be '2 h' // Object.is equality
Tests 2 failed | 1 passed (3)Green. Make them pass, directly:
export function formatDuration(minutes: number): string {
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
if (rest === 0) return `${hours} h`;
return `${hours} h ${rest} min`;
} Tests 3 passed (3)Refactor. The code works but has three return paths and a magic number. With the tests green, restructure it for clarity:
const MINUTES_PER_HOUR = 60;
/** "45 min", "1 h 30 min", or "2 h". */
export function formatDuration(totalMinutes: number): string {
const hours = Math.floor(totalMinutes / MINUTES_PER_HOUR);
const minutes = totalMinutes % MINUTES_PER_HOUR;
const parts: string[] = [];
if (hours > 0) parts.push(`${hours} h`);
if (minutes > 0 || hours === 0) parts.push(`${minutes} min`);
return parts.join(" ");
} Tests 3 passed (3)Still green, so the behavior is unchanged. Refactoring means improving structure *without* changing behavior; the tests are what let you know that's true. Notice the goal was clarity, not cleverness: a one-line version is possible, but harder to read.
Cycle 3
Red. What should happen with a negative or fractional duration? That's a design decision, and writing the test forces you to make it. Here, invalid input is a programming error and should fail loudly:
it("rejects negative or fractional minutes", () => {
expect(() => formatDuration(-5)).toThrow(RangeError);
expect(() => formatDuration(1.5)).toThrow(RangeError);
}); × rejects negative or fractional minutes 2ms
AssertionError: expected function to throw an error, but it didn't
Tests 1 failed | 3 passed (4)Green.
if (!Number.isInteger(totalMinutes) || totalMinutes < 0) throw new RangeError(`Invalid duration: ${totalMinutes}`); Tests 4 passed (4)Four small cycles produced a function with a test for every behavior, including the edge case most people forget, and a design decision recorded in a test name. At no point was there a long stretch of untested code, or a moment when you didn't know what to do next.
Why TDD improves design
- Testable by construction. If code is hard to test, you notice before writing it, and pass dependencies in instead of reaching for globals (lesson 6).
- Small steps. You always know what you're doing next, and when something breaks, it's in the last few lines. Small, green steps also make small, focused commits natural (see Git Fundamentals).
- Interfaces first. Writing the call before the implementation makes you design the function from the caller's side.
- No untested code. Every behavior exists because a test asked for it.
- Living documentation. The test names list what the code does.
When TDD fits, and when it doesn't
TDD works especially well for business rules, calculations, parsers, state machines, and bug fixes (write the failing regression test first, as in lesson 5). It fits less naturally when:
- you're exploring an unfamiliar API or prototyping an idea you'll throw away (write a spike, then delete it and rebuild with tests);
- the output is visual or subjective, like layout or animation;
- you're working with legacy code that has no seams for tests. Start by adding characterization tests that record what the code currently does, then refactor under their protection.
TDD is a discipline, not a rule for every line of code. Even teams that don't practice it strictly benefit from its core habit: see the test fail before you trust it.
Writing meaningful assertions
Good tests check behavior precisely, so they fail for the right reasons:
- Assert the outcome, not the steps.
toBe("1 h 30 min"), not "calledMath.flooronce." - One behavior per test, named as a sentence about that behavior.
- Precise matchers.
toBe(4500)rather thantoBeGreaterThan(0);toThrow(RangeError)rather thantoThrow(). - Avoid logic in tests. Loops and conditionals in a test can hide bugs of their own. Use parameterized tests (lesson 3) instead.
Keeping a test suite maintainable
A test suite is code, and it ages like code. Habits that keep it healthy:
- Refactor tests too. Remove duplication with small helpers and builders, but keep each test readable on its own.
- Name tests by behavior, so a failure message reads like a broken requirement.
- Delete tests that no longer describe required behavior, rather than updating them blindly to match new code.
- Keep tests fast, so people run them constantly. Move slow checks to integration suites.
- Fix flaky tests immediately (lesson 15); a suite people don't trust is a suite they ignore.
- Review test code with the same care as production code.
Common mistakes and troubleshooting
- Writing the code first, then the test, and calling it TDD. You lose the proof that the test can fail.
- Big steps. If a cycle takes an hour, the test was too ambitious. Split it.
- Skipping refactoring. You get tested but messy code. The refactor step is where design improves.
- Testing private details. Tests then break on every refactor, which defeats the purpose.
- Changing tests and code at the same time. During refactoring, the tests should stay the same and stay green.
- "I can't make it fail." If a new test passes immediately, either the behavior already exists (fine, keep the test as documentation) or the test doesn't check what you think. Break the code briefly to find out.
Practical exercise: a TDD kata
Build splitBill(totalCents, people) that splits a bill so the parts add up exactly to the total (the first people pay one cent more when it doesn't divide evenly), using red-green-refactor:
- Write a test for an even split; see it fail; make it pass.
- Add a test for an uneven split (1,000 cents among 3 people → 334, 333, 333); see it fail; make it pass.
- Refactor for clarity with the tests green.
- Decide what zero people and negative totals should do; write those tests first.
- Look at your test names. Do they describe the function completely?
Key takeaways
- TDD repeats red (a failing test), green (the simplest passing code), and refactor (better structure, same behavior).
- Seeing a test fail first proves it can detect the defect.
- TDD drives testable, caller-friendly design and records decisions in test names.
- It fits business logic and bug fixes best; use spikes and characterization tests elsewhere.
- Maintain tests like production code: readable, fast, precise, and trusted.
References
- Martin Fowler: Test Driven Development (opens in a new tab)
- Kent Beck: Canon TDD (opens in a new tab)
- Martin Fowler: Refactoring (opens in a new tab)
- Vitest: Getting Started (opens in a new tab)
- Martin Fowler: Self Testing Code (opens in a new tab)
What's next
Tests protect you only if they run on every change. Automated Testing in CI/CD: Coverage, Static Analysis, and Quality Gates puts them in the pipeline.

