Skip to main content

Test-Driven Development

Test-Driven Development, or TDD, is a development workflow where a developer writes a failing test before writing the production code that makes it pass.

Write one failing test
|
v
Write the smallest useful implementation
|
v
Improve the design while tests remain green
|
v
Repeat with the next behavior

One-line idea: TDD grows software in small behavior-driven steps through the repeating Red-Green-Refactor cycle.

Core Concepts​

TDD Is a Development Workflow​

TDD is not a separate test level such as unit, integration or E2E testing.

It describes when and how tests guide implementation:

Traditional test-after flow
Implementation -> Tests

TDD flow
Expected behavior -> Failing test -> Implementation -> Refactor

TDD is commonly practiced with fast unit or component tests, but the guiding test can also cover an integration boundary when that is the behavior being designed.

Why Write the Test First?​

Writing the test first forces the developer to answer:

  • What behavior is required?
  • What should the public interface look like?
  • What input and output make the behavior clear?
  • Which edge case matters next?
  • How will a caller know the operation succeeded or failed?

The test becomes an executable example of the intended contract.

TDD Does Not Mean Writing Every Test Up Front​

TDD works in small increments.

One behavior
-> one failing test
-> one small implementation
-> one refactoring step
-> next behavior

Writing a large test suite before learning from any implementation creates a long feedback delay and often locks in premature assumptions.

The Red-Green-Refactor Cycle​

Red: Write a Failing Test​

Write the smallest test that describes the next missing behavior.

Run it and confirm that it fails for the expected reason.

Expected failure:
isPalindrome is not implemented

Unexpected failure:
test file cannot import Jest configuration

Both are red, but only the first failure proves that the intended behavior is missing.

The Red phase prevents false confidence from a test that never exercised the new requirement.

Green: Make the Test Pass​

Write the simplest production code that satisfies the current behavior.

The goal is correctness and feedback, not the final perfect design.

Do not solve hypothetical future requirements.
Implement enough for the current tested contract.

All existing tests should remain green. If a new change breaks an earlier behavior, resolve the conflict before moving on.

Refactor: Improve the Design​

When the suite is green, improve code without changing its observable behavior.

Possible refactorings include:

  • rename unclear variables
  • remove duplication
  • extract a function
  • simplify conditions
  • move responsibilities to clearer modules
  • improve test readability

Run the tests during refactoring. The suite acts as a safety net, but it protects only the behaviors it actually covers.

Repeat​

Red     -> What behavior is missing?
Green -> What is the smallest correct change?
Refactor -> How can the design become clearer?

Short cycles keep failures easy to understand and changes easy to review.

Palindrome Example With Jest​

Suppose the required contract is:

  • return null for null or undefined
  • accept strings and numbers
  • return false for other types
  • ignore string casing and surrounding spaces
  • ignore a leading minus sign on numbers
  • return null when the normalized value is longer than 10 characters

These are product rules for this example, not universal palindrome rules.

First Cycle: Basic String Behavior​

Start with one failing test:

import { isPalindrome } from "./isPalindrome";

test("returns false for a non-palindrome string", () => {
expect(isPalindrome("abc")).toBe(false);
});

Run the test. It should fail because the function does not exist or has no implementation.

Write the smallest useful implementation:

export function isPalindrome(value) {
const text = String(value);
return text === [...text].reverse().join("");
}

The first test is green.

Second Cycle: Palindrome String​

Add the next behavior:

test("returns true for a palindrome string", () => {
expect(isPalindrome("aba")).toBe(true);
});

The existing implementation already satisfies it. A new test that immediately passes can still document behavior, but it did not force a production-code change.

TDD does not require intentionally breaking correct code. Continue to the next missing behavior.

Third Cycle: Missing Input​

test.each([undefined, null])(
"returns null for missing input %p",
(value) => {
expect(isPalindrome(value)).toBeNull();
},
);

The current implementation returns a boolean, so this test fails.

Add the minimum rule:

export function isPalindrome(value) {
if (value === null || value === undefined) {
return null;
}

const text = String(value);
return text === [...text].reverse().join("");
}

Fourth Cycle: Supported Types​

test.each([true, {}, () => {}])(
"returns false for unsupported value %p",
(value) => {
expect(isPalindrome(value)).toBe(false);
},
);

Add an explicit type check:

const isSupportedType = (value) =>
typeof value === "string" || typeof value === "number";

export function isPalindrome(value) {
if (value === null || value === undefined) {
return null;
}

if (!isSupportedType(value)) {
return false;
}

const text = String(value);
return text === [...text].reverse().join("");
}

Fifth Cycle: Normalization Rules​

Add focused examples:

test.each([
["Aba", true],
[" aba ", true],
[121, true],
[123, false],
[-121, true],
])("evaluates %p as %p", (value, expected) => {
expect(isPalindrome(value)).toBe(expected);
});

Update normalization:

function normalize(value) {
const text = String(value).toLowerCase().trim();
return typeof value === "number" && text.startsWith("-")
? text.slice(1)
: text;
}

Sixth Cycle: Length Rule​

test("returns null when the normalized value is longer than 10 characters", () => {
expect(isPalindrome("abcdefghijk")).toBeNull();
});

Refactored Implementation​

After all tests pass, improve the structure:

const MAX_LENGTH = 10;

const isSupportedType = (value) =>
typeof value === "string" || typeof value === "number";

const normalize = (value) => {
const text = String(value).toLowerCase().trim();
return typeof value === "number" && text.startsWith("-")
? text.slice(1)
: text;
};

export function isPalindrome(value) {
if (value === null || value === undefined) {
return null;
}

if (!isSupportedType(value)) {
return false;
}

const text = normalize(value);

if (text.length > MAX_LENGTH) {
return null;
}

return text === [...text].reverse().join("");
}

The refactoring separates validation, normalization and comparison while keeping the tested contract unchanged.

What the Example Demonstrates​

Behavior Is Defined Before Implementation​

Each test states one observable rule before production code is changed.

The API grows from examples rather than from speculative implementation details.

Edge Cases Arrive Incrementally​

Nulls, unsupported types, casing, spacing, numbers and maximum length are introduced one behavior at a time.

This makes it easier to identify which requirement caused a design change.

Tests Support Refactoring​

After the behavior is green, internal structure can change while the public result stays stable.

Tests reduce refactoring risk, but good version control, reviews and broader integration checks remain important.

Writing Good TDD Tests​

Test Observable Behavior​

Prefer this:

expect(calculateTotal(cart)).toBe(42);

Avoid tests that depend on private helpers or the exact sequence of internal function calls unless that interaction is itself the contract.

Behavior-focused tests survive more refactoring.

Give Tests Clear Names​

A useful name includes the condition and expected result.

returns null when input is missing
rejects checkout when the cart is empty
shows an error when login credentials are invalid

Avoid names such as works, test 1 or handles input.

Use Arrange-Act-Assert​

test("applies a fixed discount to the cart total", () => {
// Arrange
const cart = [{ price: 50, quantity: 2 }];

// Act
const total = calculateTotal(cart, { discount: 10 });

// Assert
expect(total).toBe(90);
});

Small tests may not need comments, but the conceptual separation keeps them readable.

Keep Feedback Fast​

TDD depends on frequent test runs. The focused suite should complete quickly enough to run after each small change.

Use broader integration and E2E suites as additional confidence rather than forcing every Red-Green cycle through a slow browser workflow.

Make Failures Easy to Diagnose​

One test should fail for one clear reason.

Avoid putting many unrelated assertions and behaviors into a single test because the first failure can hide the rest.

Keep Tests Deterministic​

Control or isolate:

  • time
  • random values
  • network responses
  • shared databases
  • process environment
  • global mutable state

A test that passes only sometimes cannot provide reliable design feedback.

TDD With React Components​

For React, begin with user-visible behavior rather than component internals.

Suppose a counter must start at zero and increment when the user clicks a button.

Red​

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Counter } from "./Counter";

test("increments the count when the button is clicked", async () => {
const user = userEvent.setup();
render(<Counter />);

expect(screen.getByText("Count: 0")).toBeInTheDocument();

await user.click(screen.getByRole("button", { name: "Increment" }));

expect(screen.getByText("Count: 1")).toBeInTheDocument();
});

Green​

import { useState } from "react";

export function Counter() {
const [count, setCount] = useState(0);

return (
<section>
<p>Count: {count}</p>
<button type="button" onClick={() => setCount(count + 1)}>
Increment
</button>
</section>
);
}

Refactor​

Refactor only when it improves the design. A tiny component may already be clear.

TDD does not require extracting abstractions without a concrete design pressure.

Test Doubles and Dependencies​

External dependencies can make a focused test slow or unpredictable.

Common test doubles include:

DoublePurpose
StubReturns a controlled result
FakeProvides a lightweight working implementation
SpyRecords calls for later verification
MockRepresents an expected interaction

Example dependency boundary:

export async function registerUser(input, userRepository) {
const existingUser = await userRepository.findByEmail(input.email);

if (existingUser) {
return { ok: false, reason: "EMAIL_ALREADY_USED" };
}

const user = await userRepository.create(input);
return { ok: true, user };
}

The test can provide a small fake repository without accessing a real database.

Do not mock every internal function. Excessive mocking couples tests to implementation and makes refactoring harder.

Use integration tests to confirm that real boundaries such as databases, HTTP clients and queues work together correctly.

Outside-In and Inside-Out TDD​

Inside-Out​

Begin with a small domain object or function and build outward.

Domain rule -> service -> adapter -> UI

This works well when the core behavior is understood and can be modeled independently.

Outside-In​

Begin with an externally visible behavior and use test doubles to discover required collaborators.

User or API behavior -> application service -> domain collaborators

This keeps work aligned with a complete outcome but requires care to avoid interaction-heavy mocks.

Both approaches can follow Red-Green-Refactor. Choose the direction that makes the next behavior clearest.

TDD and Legacy Code​

Legacy code often lacks tests and may be difficult to change safely.

A practical workflow is:

  1. identify the behavior that must remain unchanged
  2. add a characterization test for current behavior
  3. create a small dependency boundary if necessary
  4. make the desired change through Red-Green-Refactor
  5. add integration coverage around high-risk connections

A characterization test records what the system currently does. It does not automatically prove that current behavior is ideal.

TDD, Coverage and CI​

Code Coverage​

Coverage reports which code ran during tests. It can reveal untested paths, but a high percentage does not prove that assertions are meaningful.

Coverage asks: Did the test execute this code?
Quality asks: Did the test verify important behavior?

Use coverage as diagnostic information, not the only target.

Continuous Integration​

TDD's fast test suite should run in CI for every relevant change.

Local Red-Green-Refactor cycles
|
v
Push or pull request
|
v
Unit and component tests
|
v
Integration and E2E checks

CI protects the shared codebase, while local fast feedback supports the development cycle.

Benefits and Trade-Offs​

Benefits​

  • clarifies behavior before implementation
  • encourages small public interfaces
  • catches regressions quickly
  • supports confident refactoring
  • produces executable examples
  • reduces unnecessary production code
  • improves separation when dependencies are difficult to test

Trade-Offs​

  • requires practice to choose the next useful test
  • weak tests can lock in implementation details
  • slow suites make the cycle frustrating
  • unclear requirements still require product discussion
  • UI, concurrency and distributed behavior can need broader tests
  • existing tightly coupled code may require preparatory refactoring

TDD improves design through feedback; it does not automatically guarantee good architecture or bug-free software.

When TDD Is Most Useful​

TDD is especially useful for:

  • domain rules with clear examples
  • data transformations
  • validation
  • reducers and state machines
  • bug fixes that need regression protection
  • reusable APIs and libraries
  • component behavior
  • algorithmic edge cases

Exploratory prototypes may begin with discovery rather than strict TDD. Once the desired behavior becomes clearer, capture it with tests before turning the prototype into maintained production code.

Common Mistakes​

MistakeBetter approach
Writing production code before seeing the test failConfirm a meaningful Red phase
Writing the entire test suite firstAdd one small behavior per cycle
Implementing future requirements during GreenWrite only enough code for the current contract
Skipping Refactor because tests passImprove duplication, names and boundaries while green
Refactoring while tests are redRestore correctness first so failures remain informative
Testing private implementation detailsTest observable inputs, outputs and user behavior
Mocking every collaboratorMock true boundaries and keep important integration tests
Treating coverage percentage as test qualityVerify meaningful behaviors and edge cases
Keeping slow tests in the inner loopSeparate fast feedback from broader verification
Combining many behaviors in one testKeep failures focused and diagnostic
Changing tests only to make a failure disappearDecide whether the requirement or implementation is wrong
Assuming TDD replaces integration and E2E testsUse the complete testing strategy required by the system

Summary​

Test-Driven Development builds software through short behavior-first feedback cycles.

Choose the next observable behavior
|
v
Write a small test and see the expected failure
|
v
Implement the simplest correct behavior
|
v
Run the complete relevant test suite
|
v
Refactor code and tests while green
|
v
Repeat with the next behavior

Good TDD is not about maximizing the number of tests. It is about using precise examples and rapid feedback to create code that is correct, understandable and safe to change.