JS-210 · Lesson 10 of 12 · 27 min
Test-driven development
▶ Video coming soon A video version of this lesson is on the way.
On Thursday, November 18, Lucy Tran sends Brightwater a new rule for the volunteer sign-up form, ahead of the hamper drive. A volunteer must not be able to sign up for two shifts that overlap, but back-to-back shifts are fine: someone can work the warehouse from 9 to 11:30 and the pick-up desk from 11:30 to 2. Gareth reads it aloud and asks Mira not to open the sign-up code yet. "Write down what the rule means first, as tests," he says. "Then write just enough code to make them pass. Then tidy up. Today you do it the other way round."
Writing the test before the code is called test-driven development, or TDD. This lesson explains the red, green, refactor cycle, works through Lucy's overlap rule one test at a time, shows how tests written first shape the design of the code, adds property-based tests that check rules against hundreds of generated inputs, and discusses when TDD is worth it and when it is not.
Red, green, refactor
TDD was popularized by Kent Beck around 2000 as part of Extreme Programming. Its cycle has three steps, repeated in very small increments.
- Red. Write one small test for the next piece of behaviour, and run it. It must fail, and fail for the expected reason. A test that passes before the code exists is not testing anything.
- Green. Write the simplest code that makes the test pass, even if it is crude. Run all of the tests.
- Refactor. With every test passing, improve the code: remove duplication, choose clearer names, simplify. Run the tests after each change. If they stay green, the behaviour has not changed.
The cycle is short, often a few minutes. Each turn adds one behaviour, and at every moment there is at most one failing test, so the next step is always clear. The tests that pile up become a precise description of what the code does, written before anyone could be tempted to describe the code they happened to write.
Lucy's rule as a list of examples
Before any test, Mira writes the rule as examples in plain words, with times in minutes since midnight to keep the arithmetic simple. Lucy's email becomes a short list.
| Shift A | Shift B | Overlap? | Why |
|---|---|---|---|
| 9:00–11:30 | 13:00–15:00 | No | B starts after A ends |
| 9:00–11:30 | 11:00–13:00 | Yes | B starts before A ends |
| 9:00–11:30 | 11:30–14:00 | No | Back to back is allowed |
| 13:00–15:00 | 9:00–11:30 | No | The order of the two shifts does not matter |
| 9:00–17:00 | 12:00–13:00 | Yes | B is inside A |
| 9:00–11:30 | 9:00–11:30 | Yes | The same shift twice |
Each row will become one test, and they will be added one at a time. The first test is the simplest example of the most basic behaviour: two shifts far apart do not overlap.
The first turns of the cycle
Mira starts with a stub that always returns true, the opposite of what the first test expects, so that she sees the test fail for the right reason.
const results = [];
function test(name, fn) { try { fn(); results.push('\u2713 ' + name); } catch (e) { results.push('\u2717 ' + name + ' - ' + e.message); } }
function expectEqual(actual, expected) { if (actual !== expected) throw new Error(`expected ${expected}, received ${actual}`); }
const t = (h, m = 0) => h * 60 + m;
// Red: the function exists but does nothing useful yet.
function overlaps(a, b) {
return true;
}
test('shifts far apart do not overlap', () => expectEqual(overlaps({ start: t(9), end: t(11, 30) }, { start: t(13), end: t(15) }), false));
console.log(results.join('\n'));✗ shifts far apart do not overlap - expected false, received true
What this code does
The small test helper records a tick or a cross with a message for each test. The stub always says shifts overlap, so the first test fails, and the message shows the expected and received values. Seeing the failure first proves the test can detect a wrong answer.
The simplest code that passes is almost embarrassingly simple, and TDD says to write it anyway. Mira compares the second shift's start with the first shift's end. That is enough for the first test, and the second test, which she adds next, shows that it is also nearly right.
const results = [];
function test(name, fn) { try { fn(); results.push('\u2713 ' + name); } catch (e) { results.push('\u2717 ' + name + ' - ' + e.message); } }
function expectEqual(actual, expected) { if (actual !== expected) throw new Error(`expected ${expected}, received ${actual}`); }
const t = (h, m = 0) => h * 60 + m;
// Green: just enough to pass the tests so far.
function overlaps(a, b) {
return b.start < a.end;
}
test('shifts far apart do not overlap', () => expectEqual(overlaps({ start: t(9), end: t(11, 30) }, { start: t(13), end: t(15) }), false));
test('a shift that starts before the other ends overlaps', () => expectEqual(overlaps({ start: t(9), end: t(11, 30) }, { start: t(11), end: t(13) }), true));
test('back-to-back shifts do not overlap', () => expectEqual(overlaps({ start: t(9), end: t(11, 30) }, { start: t(11, 30), end: t(14) }), false));
test('the order of the shifts does not matter', () => expectEqual(overlaps({ start: t(13), end: t(15) }, { start: t(9), end: t(11, 30) }), false));
console.log(results.join('\n'));✓ shifts far apart do not overlap ✓ a shift that starts before the other ends overlaps ✓ back-to-back shifts do not overlap ✗ the order of the shifts does not matter - expected false, received true
What this code does
With b.start < a.end the first three tests pass, including back-to-back shifts, because 11:30 is not less than 11:30. The fourth test swaps the two shifts from the first test, and the code wrongly says they overlap, because it only checks whether the second shift starts before the first one ends. The failing test points straight at the missing half of the rule.
The fourth test fails, which is the point: the code made an assumption, that the first shift comes first, which Lucy's rule never made. The fix is the standard test for two intervals: they overlap when each one starts before the other ends.
const results = [];
function test(name, fn) { try { fn(); results.push('\u2713 ' + name); } catch (e) { results.push('\u2717 ' + name + ' - ' + e.message); } }
function expectEqual(actual, expected) { if (actual !== expected) throw new Error(`expected ${expected}, received ${actual}`); }
const t = (h, m = 0) => h * 60 + m;
function overlaps(a, b) {
return a.start < b.end && b.start < a.end;
}
const cases = [
['shifts far apart do not overlap', [t(9), t(11, 30)], [t(13), t(15)], false],
['a shift that starts before the other ends overlaps', [t(9), t(11, 30)], [t(11), t(13)], true],
['back-to-back shifts do not overlap', [t(9), t(11, 30)], [t(11, 30), t(14)], false],
['the order of the shifts does not matter', [t(13), t(15)], [t(9), t(11, 30)], false],
['a shift inside another overlaps', [t(9), t(17)], [t(12), t(13)], true],
['the same shift twice overlaps', [t(9), t(11, 30)], [t(9), t(11, 30)], true],
];
for (const [name, [as, ae], [bs, be], want] of cases) {
test(name, () => expectEqual(overlaps({ start: as, end: ae }, { start: bs, end: be }), want));
}
console.log(results.join('\n'));✓ shifts far apart do not overlap ✓ a shift that starts before the other ends overlaps ✓ back-to-back shifts do not overlap ✓ the order of the shifts does not matter ✓ a shift inside another overlaps ✓ the same shift twice overlaps
What this code does
Two intervals overlap exactly when each starts before the other ends, and the strict less-than keeps back-to-back shifts apart. Every row of Mira's table is now a test case, and all six pass. Writing the cases as a table makes it easy to add the next example Lucy thinks of.
The last two tests, a shift inside another and the same shift twice, passed as soon as Mira added them. In strict TDD a test that passes immediately is a warning sign that it may not test anything new. Here they are worth keeping because they document cases from Lucy's email, and Mira checks that they can fail by briefly breaking the code. That habit, making sure a test can fail, matters more than following the cycle to the letter.
Refactor
With the tests green, Mira turns to the code that uses overlaps: the function that checks a new sign-up against a volunteer's existing shifts and returns the clashes, so that the form can say which shift is in the way. Her first version works, and the tests let her tidy it with confidence.
const results = [];
function test(name, fn) { try { fn(); results.push('\u2713 ' + name); } catch (e) { results.push('\u2717 ' + name + ' - ' + e.message); } }
function expectEqual(actual, expected) { if (actual !== expected) throw new Error(`expected ${expected}, received ${actual}`); }
const t = (h, m = 0) => h * 60 + m;
const overlaps = (a, b) => a.start < b.end && b.start < a.end;
// Before: works, but the loop and the date check are tangled together.
function clashesBefore(existing, proposed) {
const out = [];
for (let i = 0; i < existing.length; i++) {
if (existing[i].date === proposed.date) {
if (overlaps(existing[i], proposed) === true) out.push(existing[i].area);
}
}
return out;
}
// After: the same result, said directly.
const sameDay = (a, b) => a.date === b.date;
function clashes(existing, proposed) {
return existing.filter((s) => sameDay(s, proposed) && overlaps(s, proposed)).map((s) => s.area);
}
const anaShifts = [
{ area: 'Warehouse', date: '2027-12-18', start: t(9), end: t(11, 30) },
{ area: 'Pick-up desk', date: '2027-12-18', start: t(13), end: t(15) },
{ area: 'Warehouse', date: '2027-12-19', start: t(9), end: t(11, 30) },
];
const proposed = { area: 'Lunch counter', date: '2027-12-18', start: t(11), end: t(13, 30) };
for (const fn of [clashesBefore, clashes]) {
test(fn.name + ': finds both clashes on the same day', () => expectEqual(fn(anaShifts, proposed).join(', '), 'Warehouse, Pick-up desk'));
test(fn.name + ': ignores other days', () => expectEqual(fn(anaShifts, { ...proposed, date: '2027-12-20' }).length, 0));
}
console.log(results.join('\n'));✓ clashesBefore: finds both clashes on the same day ✓ clashesBefore: ignores other days ✓ clashes: finds both clashes on the same day ✓ clashes: ignores other days
What this code does
clashesBefore and clashes do the same job, one with an index loop and nested conditions and the other with filter, map and two small named helpers. The same tests run against both versions and pass, which is the evidence that the refactoring changed the shape of the code but not its behaviour. In the real project the old version is simply replaced and the tests are run again.
Refactoring is the step people skip, and it is the step that keeps code healthy. Without tests, every tidy-up is a risk, so code is left as it first worked. With tests, Mira can rename, split and simplify in small steps and know within a second whether she broke anything.
How tests shape design
Writing the test first means using the code before it exists, from the point of view of the code that will call it. That pushes the design in useful directions. Mira wanted overlaps to take two plain objects with start and end, because that was easy to write in a test, and the result is a small function with no dependencies that the form, the dashboard and Theo's server checks can all share. The clashes function takes the existing shifts as a parameter instead of loading them, because the test needed to pass them in, which is the dependency injection of Lesson 7 arrived at naturally.
Code that is hard to test is usually telling you something about its design: it does too much, or it reaches out for things it should be given. TDD notices that at the moment the code is being written, which is the cheapest moment to change it.
Property-based testing
Example tests check the cases someone thought of. Property-based testing checks a rule, a property, against many generated inputs, including ones nobody would think of. For overlaps, two properties follow from Lucy's rule: the order of the shifts never matters, so overlaps(a, b) equals overlaps(b, a); and a shift that ends exactly when another starts never overlaps it. A property test generates hundreds of random shifts and checks both. The fast-check library does this for Vitest and Jest, and when it finds a failure it shrinks the input to the smallest example that still fails.
// A seeded random generator, so the same inputs are generated on every run.
function makeRandom(seed) {
return () => { seed = (seed * 1664525 + 1013904223) % 4294967296; return seed / 4294967296; };
}
const random = makeRandom(2027);
const int = (min, max) => min + Math.floor(random() * (max - min + 1));
function randomShift() {
const start = int(6 * 60, 20 * 60);
return { start, end: start + int(1, 6) * 30 };
}
function checkProperty(name, runs, property) {
for (let i = 1; i <= runs; i++) {
const a = randomShift(), b = randomShift();
if (!property(a, b)) return `${name}: FAILED on run ${i} with ${JSON.stringify(a)} and ${JSON.stringify(b)}`;
}
return `${name}: held for ${runs} random pairs`;
}
const good = (a, b) => a.start < b.end && b.start < a.end;
const buggy = (a, b) => b.start < a.end; // the early version that only looked one way
console.log(checkProperty('good overlaps is symmetric', 500, (a, b) => good(a, b) === good(b, a)));
console.log(checkProperty('back to back never overlaps', 500, (a) => !good(a, { start: a.end, end: a.end + 60 })));
console.log(checkProperty('buggy overlaps is symmetric', 500, (a, b) => buggy(a, b) === buggy(b, a)));good overlaps is symmetric: held for 500 random pairs
back to back never overlaps: held for 500 random pairs
buggy overlaps is symmetric: FAILED on run 1 with {"start":686,"end":836} and {"start":863,"end":1013}What this code does
The seeded generator produces random-looking shift times that are the same on every run, so a failure can be reproduced. checkProperty draws pairs of shifts and stops at the first pair that breaks the property. The correct function holds for all 500 pairs on both properties, while the early buggy version is caught on its first run with a concrete pair of shifts that shows the problem.
import fc from 'fast-check';
import { expect, test } from 'vitest';
import { overlaps } from './overlaps';
const shift = fc
.record({ start: fc.integer({ min: 0, max: 1380 }), length: fc.integer({ min: 15, max: 600 }) })
.map(({ start, length }) => ({ start, end: start + length }));
test('overlap does not depend on the order of the shifts', () => {
fc.assert(fc.property(shift, shift, (a, b) => overlaps(a, b) === overlaps(b, a)));
});
test('back-to-back shifts never overlap', () => {
fc.assert(fc.property(shift, fc.integer({ min: 15, max: 600 }), (a, length) =>
!overlaps(a, { start: a.end, end: a.end + length })));
});What this code does
fc.record and map build an arbitrary, a generator of random shifts with a start time and a length. fc.property says which inputs to generate and what must be true for each, and fc.assert runs it a hundred times by default. If a run fails, fast-check shrinks the shifts towards the simplest failing pair and reports it with a seed that replays the same run.
Regression tests
When a bug is found, the first step in Brightwater's process is a failing test that reproduces it. That test is red; the fix turns it green; and from then on it is a regression test that stops the bug from coming back. The cent-short totals from Lesson 6 now have one, and so will every bug Rosa reports. Writing the test first also confirms that the bug is understood, because a test that cannot reproduce the problem means the cause has not been found yet.
When TDD helps and when it does not
TDD is a technique, not a law, and experienced developers use it where it pays. Gareth's view, which matches that of most teams Brightwater works with:
- It helps most with logic that has clear rules: calculations, validation, parsing, scheduling rules like Lucy's, and bug fixes.
- It helps when requirements are precise, because each example becomes a test, and when they are vague, because writing the tests forces the questions out early. Mira sent Lucy one question while writing the table: whether a shift ending at midnight counts as that day. The answer became a test.
- It helps less with exploratory work, such as trying three layouts for the dashboard, where nobody yet knows what the right behaviour is. Write the tests once the design settles.
- It is awkward for code that is mostly wiring, such as the DOM code that connects buttons to the order, where Lesson 8's tests after the fact are fine.
Whatever the order, the goal is the same: behaviour that is written down as tests that can fail, and code that is changed in small steps while they pass.
Common mistakes
MistakeA new test that passes straight away is a good start.
InsteadIn TDD a new test should fail first. If it passes, check that it can fail by briefly breaking the code.
MistakeGreen means the code is finished.
InsteadGreen means it works. Refactor next, while the tests protect you.
MistakeWrite the whole function, then all the tests.
InsteadAdd one small behaviour at a time: one failing test, the simplest code that passes, then tidy up.
MistakeRandom tests are flaky.
InsteadUse a seeded generator or fast-check, which reports the seed, so every failure can be replayed.
MistakeFix the bug, then add a test if there is time.
InsteadWrite a failing test that reproduces the bug first; it proves the cause and prevents a regression.
Summary and key terms
- Test-driven development writes a failing test before the code, in a cycle of red, green and refactor: write one small failing test, write the simplest code that passes, then improve the code while all tests stay green.
- Each turn adds one behaviour, and the tests become a precise description of it.
- Turning a rule into a table of examples first, as with Lucy's overlap rule, makes each example a test.
- Two intervals overlap when each starts before the other ends; strict comparison keeps back-to-back shifts apart.
- Tests should be seen to fail.
- Refactoring under tests changes structure without changing behaviour.
- Writing tests first pushes code towards small functions that receive their dependencies.
- Property-based tests check rules, such as symmetry, against many generated inputs, and fast-check shrinks failures to a minimal example.
- Every bug fix starts with a failing regression test.
- TDD helps most with clear rules and bug fixes and less with exploratory or wiring code.
- test-driven development
- Writing a failing test before the code that makes it pass, in small steps.
- red, green, refactor
- The TDD cycle: a failing test, the simplest passing code, then improvement.
- refactoring
- Changing the structure of code without changing its behaviour.
- property
- A rule that should hold for every valid input, such as the order of arguments not mattering.
- property-based testing
- Testing a property against many generated inputs.
- arbitrary
- In fast-check, a generator of random values of some shape.
- shrinking
- Reducing a failing generated input to the simplest one that still fails.
- seed
- A starting value that makes a random generator produce the same sequence each time.
- regression test
- A test that reproduces a fixed bug so that it cannot return unnoticed.
- interval
- A range with a start and an end, such as a shift.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why must a new test fail before the code is written?
Show answer
To prove that it can detect the missing behaviour; a test that always passes tests nothing.
Write the overlap condition for shifts a and b.
Show answer
a.start < b.end && b.start < a.end.
What is the refactor step for?
Show answer
Improving the code's structure while the passing tests confirm that behaviour is unchanged.
Name a property of the overlaps function.
Show answer
It is symmetric: overlaps(a, b) === overlaps(b, a). Or: back-to-back shifts never overlap.
What is the first thing to do when Rosa reports a bug?
Show answer
Write a failing test that reproduces it.
Try it yourself
Parse a shift time
Lucy's spreadsheet gives shift times as text such as '9:00', '11:30' and '2:15 pm'. The tests below were written first. Write toMinutes(text) so that it returns minutes since midnight and all of the tests pass.
Times without am or pm are on the 24-hour clock. 12:00 pm is noon and 12:00 am is midnight.
const results = [];
function test(name, fn) { try { fn(); results.push('\u2713 ' + name); } catch (e) { results.push('\u2717 ' + name + ' - ' + e.message); } }
function expectEqual(actual, expected) { if (actual !== expected) throw new Error(`expected ${expected}, received ${actual}`); }
function toMinutes(text) {
return 0;
}
test('morning time', () => expectEqual(toMinutes('9:00'), 540));
test('minutes count', () => expectEqual(toMinutes('11:30'), 690));
test('24-hour afternoon', () => expectEqual(toMinutes('14:15'), 855));
test('pm adds twelve hours', () => expectEqual(toMinutes('2:15 pm'), 855));
test('noon', () => expectEqual(toMinutes('12:00 pm'), 720));
test('midnight', () => expectEqual(toMinutes('12:00 am'), 0));
test('spaces and capitals', () => expectEqual(toMinutes(' 9:05 AM '), 545));
console.log(results.join('\n'));Try it yourself
Make the property hold
busyMinutes(shifts) should return the total number of minutes a volunteer is busy, counting time covered by overlapping shifts only once. The property test checks it against a slow but obviously correct version on 300 generated sets of shifts, and the two examples check known answers.
The starter simply adds up the lengths, which double-counts overlaps. Fix it by sorting the shifts by start time and merging overlapping ones as you go.
function makeRandom(seed) { return () => { seed = (seed * 1664525 + 1013904223) % 4294967296; return seed / 4294967296; }; }
const random = makeRandom(7);
const int = (min, max) => min + Math.floor(random() * (max - min + 1));
function busyMinutes(shifts) {
return shifts.reduce((sum, s) => sum + (s.end - s.start), 0);
}
// Slow but obviously correct: mark every minute.
function busySlow(shifts) {
const busy = new Set();
for (const s of shifts) for (let m = s.start; m < s.end; m++) busy.add(m);
return busy.size;
}
console.log(busyMinutes([{ start: 540, end: 690 }, { start: 660, end: 780 }]));
console.log(busyMinutes([{ start: 540, end: 690 }, { start: 690, end: 780 }]));
let failure = null;
for (let run = 1; run <= 300 && !failure; run++) {
const shifts = Array.from({ length: int(1, 5) }, () => { const start = int(360, 1200); return { start, end: start + int(1, 8) * 30 }; });
if (busyMinutes(shifts) !== busySlow(shifts)) failure = run;
}
console.log(failure ? 'property failed on run ' + failure : 'property held for 300 runs');Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.