Skip to content
Velloreth
Programming 7 min read

Test-Driven Development: A Practical Introduction

TDD is a short red-green-refactor cycle that shapes design as much as it verifies code. Learn the loop, the benefits, and the common objections.

By

The cycle

Test-driven development is a short repeating cycle with three steps.

Red. Write a test for behaviour that does not exist yet. Run it. It fails.

Green. Write the simplest code that makes the test pass. Do not worry about elegance.

Refactor. Improve the code — extract, rename, simplify — while keeping the test green.

Then repeat with the next piece of behaviour.

The cycle is short. A step should take minutes, not hours. The point of keeping it short is that you always have a working state to return to, and a failure is always attributable to the last small change.

A worked example

Suppose you need a function that formats a duration in seconds as a human-readable string.

Red. Write the test first.

test('formats seconds under a minute', () => {
  expect(formatDuration(45)).toBe('45s');
});

Run it. It fails because formatDuration does not exist. That failure is the point — it confirms the test is actually testing something.

Green. Write the minimum code.

function formatDuration(seconds: number): string {
  return `${seconds}s`;
}

The test passes. The code is not complete, but it satisfies the current test.

Refactor. Nothing to improve yet. Move on.

Red. Next case.

test('formats minutes and seconds', () => {
  expect(formatDuration(125)).toBe('2m 5s');
});

Fails. Green:

function formatDuration(seconds: number): string {
  const minutes = Math.floor(seconds / 60);
  const remaining = seconds % 60;
  if (minutes === 0) return `${remaining}s`;
  return `${minutes}m ${remaining}s`;
}

Both tests pass. Refactor: the function is still readable, so leave it.

Red. Next case.

test('formats hours', () => {
  expect(formatDuration(3725)).toBe('1h 2m 5s');
});

And so on. Each cycle adds one behaviour, and the test suite grows alongside the code.

Why write the test first

The order matters, and the reason is design.

It forces you to decide the interface. Before writing the implementation, you must decide what the function is called, what it takes, and what it returns. That decision is easier to make well when you are thinking as a caller.

// Writing the test first makes you ask:
// - What should this be called?
// - What does it take?
// - What does it return?
// - What does it do on bad input?
expect(formatDuration(125)).toBe('2m 5s');

It surfaces coupling. If a function is hard to test, it is usually because it is tightly coupled to something — a database, a clock, a global. Writing the test first makes that coupling visible before you build on it.

It guarantees the test can fail. A test written after the code might pass for the wrong reason. A test written first has been observed failing, so you know it tests something.

It prevents over-engineering. You write only the code needed to pass the current test, which keeps the implementation minimal.

The design pressure

The most valuable effect of TDD is not the tests. It is the design pressure.

Code that is hard to test is usually badly designed. If a function reaches for a global database connection, you cannot test it without a database. If it reads the clock directly, you cannot test time-dependent behaviour. If it does five things, you need five tests with complex setup.

Writing the test first makes these problems appear immediately, while they are cheap to fix. The fix is usually dependency injection: take the dependency as a parameter.

// Hard to test: reaches for the global clock
function isExpired(expiresAt: Date): boolean {
  return new Date() > expiresAt;
}

// Easy to test: the clock is injected
function isExpired(expiresAt: Date, now: Date): boolean {
  return now > expiresAt;
}

The second version is testable, and it is also better designed — it is a pure function with no hidden dependency.

Keeping steps small

The discipline that makes TDD work is small steps.

Bad: write five tests, then implement everything, then run the suite.

Good: write one test, run it, implement, run it, refactor, run it, repeat.

The reason is diagnostic. If you write five tests and then implement, a failure could be in any of the five behaviours. If you write one test at a time, a failure is always about the behaviour you just added.

Small steps also mean you are never far from a working state. If you get stuck, you can revert the last few minutes and try a different approach.

Common objections

“It slows me down.” In the short term, yes — you write the test before the code. In the medium term, the tests catch regressions and the design pressure reduces rework. The net effect depends on how long the code lives and how often it changes.

“I do not know what to test yet.” This is a real signal. If you cannot state the expected behaviour, the requirement is unclear. TDD surfaces that early, which is useful.

“The tests are hard to write.” That is the design pressure working. Hard-to-test code is usually badly coupled, and the difficulty is telling you something.

“I write tests after, and that works.” It can. Writing tests after verifies what you built; writing them first shapes what you build. Both have value, and the second is the part TDD adds.

“It does not work for UI.” Largely true. UI layout is visual and exploratory, and the requirements emerge from trying things. TDD suits logic-heavy code with clear inputs and outputs.

When TDD fits

Good fit:

  • Business logic with clear rules.
  • Parsers, formatters, and calculators.
  • Algorithms and data transformations.
  • Bug fixes — write a failing test that reproduces the bug, then fix it.
  • APIs with defined contracts.

Poor fit:

  • Exploratory prototyping where requirements are unknown.
  • UI layout and visual design.
  • Spike work to evaluate a library.
  • Code that is about to be thrown away.

The pragmatic approach is to use TDD where it fits and not where it does not. Most developers who adopt it use it for logic and skip it for exploration.

TDD for bug fixes

One of the highest-value applications. When a bug is reported:

  1. Write a test that reproduces it. The test fails, confirming you have reproduced the bug.
  2. Fix the bug. The test passes.
  3. Keep the test. It now guards against the bug returning.

This is valuable because it proves the fix addresses the reported problem, and it prevents regression. A bug that has been fixed once and returns is a bug that was never tested.

Practical guidance

  • Keep cycles short — minutes, not hours.
  • Write the test first and watch it fail.
  • Write the minimum code to pass, then refactor.
  • Let hard-to-test code tell you about coupling.
  • Use TDD for logic, and skip it for exploration and UI.
  • Write a failing test for every bug fix.
  • Do not chase coverage numbers — test behaviour that matters.
  • Treat TDD as a tool, not a rule.

For the related practices, see unit testing basics and mocking and stubbing. For the broader context, refactoring basics and code coverage myths.

Quotable summary

Test-driven development is a short red-green-refactor cycle: write a failing test, make it pass with the simplest code, then refactor with the test as a safety net. Writing the test first forces you to decide the interface before the implementation, guarantees the test can fail, and prevents over-engineering. The most valuable effect is design pressure, because code that is hard to test is usually badly coupled, and the difficulty appears while it is still cheap to fix. Keep steps small — minutes per cycle — so a failure is always attributable to the last change and you are never far from a working state. TDD suits logic-heavy code with clear requirements and is less useful for exploratory work, prototypes, and UI layout, so treat it as a tool rather than a rule.

Frequently asked questions

What is test-driven development?
TDD is a development cycle where you write a failing test before the code, then write the minimum code to pass it, then refactor. The cycle repeats in short steps, usually minutes long.
What are the three steps of TDD?
Red: write a test that fails. Green: write the simplest code that makes it pass. Refactor: improve the code while keeping the test green. Then repeat.
Does TDD really improve code quality?
Studies show a modest reduction in defects and a clearer design, though results vary. The most consistent benefit is that writing the test first forces you to think about the interface and the edge cases before implementing.
Is TDD always worth it?
No. It suits logic-heavy code with clear requirements. It is less useful for exploratory work, prototypes, and UI layout, where the requirements emerge from trying things.
How do I start with TDD?
Pick a small, well-defined function. Write a test for the simplest case, watch it fail, write the minimum code to pass, then add the next case. Keep each cycle under a few minutes.
What is the difference between TDD and just writing tests?
Writing tests after the code verifies what you built. TDD writes the test first, which shapes what you build and forces you to consider the interface and edge cases before committing to an implementation.