Lesson 272 of 296
Test-driven development (TDD)
What you will learn
- The red, green, refactor cycle
- A complete TDD example
- Benefits and criticisms of TDD
- When TDD helps most
- Behaviour-driven development (BDD) in brief
On this page
The cycle
Test-driven development means writing a failing test first, then the simplest code that passes it, then improving the code:
| Step | Do | Why |
|---|---|---|
| Red | Write a small test for the next bit of behaviour. Run it; see it fail | Proves the test can fail and describes exactly what you want |
| Green | Write the minimum code to make it pass | Keeps you focused; no speculative code |
| Refactor | Clean up code and tests while all tests stay green | Design improves continuously, safely |
Repeat in small steps, often every few minutes.
Example: a password strength checker
Requirement: a password is valid if it has at least 12 characters and is not in a list of common passwords; return a list of problems.
Red 1: the test for length.
it("rejects passwords shorter than 12 characters", () => {
expect(passwordProblems("short")).toEqual(["Use at least 12 characters"]);
});It fails: passwordProblems does not exist.
Green 1: the simplest code:
function passwordProblems(password: string): string[] {
return password.length < 12 ? ["Use at least 12 characters"] : [];
}Red 2: it("accepts a long uncommon password", ...) passes already (no new code needed). Red 3: "rejects common passwords even when long": passwordProblems("passwordpassword") should report it. Fails.
Green 3 and Refactor: the final version, after refactoring into a list of rules:
const COMMON_PASSWORDS = new Set(["passwordpassword", "123456789012", "qwertyuiopas", "letmeinletmein"]);
type Rule = (password: string) => string | null;
const rules: Rule[] = [
(p) => (p.length < 12 ? "Use at least 12 characters" : null),
(p) => (COMMON_PASSWORDS.has(p.toLowerCase()) ? "This password is too common" : null)
];
export function passwordProblems(password: string): string[] {
return rules.map((rule) => rule(password)).filter((problem): problem is string => problem !== null);
}And the tests:
import { describe, it, expect } from "vitest";
describe("passwordProblems", () => {
it("rejects passwords shorter than 12 characters", () => {
expect(passwordProblems("short")).toEqual(["Use at least 12 characters"]);
});
it("accepts a long uncommon password", () => {
expect(passwordProblems("correct horse battery")).toEqual([]);
});
it("rejects common passwords even when long, ignoring case", () => {
expect(passwordProblems("PasswordPassword")).toEqual(["This password is too common"]);
});
it("reports every problem at once", () => {
expect(passwordProblems("")).toEqual(["Use at least 12 characters"]);
});
});Adding a new rule now means one test and one array entry (Open/Closed, Lesson 267). The common-password list is tiny for the example; a real one checks a large breached-password list (Lesson 201).
Benefits and criticisms
| Benefits | Criticisms |
|---|---|
| Every behaviour has a test; strong regression safety | Slower at first; feels unnatural until practised |
| Forces small, testable, decoupled designs | Hard when exploring an unclear problem or prototyping |
| Clear definition of "done" for each step | Badly done, it produces tests coupled to implementation |
| Fewer debugging sessions | UI layout and visual work are awkward to drive by tests |
Pragmatic teams use TDD for business logic, bug fixes (write a test reproducing the bug first, then fix it: the bug can never silently return) and algorithms, and write tests alongside or just after code for UI and exploratory work.
TDD is useful in live coding interviews too: writing a couple of quick test cases first clarifies the problem and shows professional habits (Lesson 151).
BDD in brief
Behaviour-driven development extends TDD with tests written in business language, often in the Given / When / Then format, sometimes with tools such as Cucumber:
Given a basket worth £45
When the customer chooses standard delivery
Then the delivery cost is £3.99It encourages developers, testers and product people to agree on behaviour before building. Even without tools, naming tests in this style helps.
How to say it in an interview
"TDD is red, green, refactor: write a small failing test for the next behaviour, write the minimum code to pass it, then refactor with the tests green. It gives full regression coverage, pushes towards small decoupled designs and makes bug fixes permanent, since I first write a test that reproduces the bug. It is slower at first and less natural for exploratory or visual work, so I use it mainly for business logic, algorithms and bug fixes. BDD describes behaviour in Given, When, Then terms shared with the business."
Key words
| Word | Meaning |
|---|---|
| TDD | Writing a failing test before the code |
| Red / green / refactor | Fail, pass, then improve |
| Regression test | A test that stops a fixed bug returning |
| BDD | Behaviour-driven development, using business language |
| Given / When / Then | Context, action, expected outcome |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.