JS-210 · Lesson 12 of 12 · 26 min
Capstone: a tested and tooled project
▶ Video coming soon A video version of this lesson is on the way.
The capstone is planned for two sessions, Tuesday, November 30 and Thursday, December 2, 2027, with the review on Friday, December 3, a few weeks before the hamper drive. The brief Gareth writes is one paragraph: bring the counter page fully up to the studio's standard, so that any developer at Brightwater can change it on the morning of the hamper drive and know within five minutes whether the change is safe. Then apply the same setup to riverside-data and the office dashboard.
This lesson follows that plan. It sets out the standard as a checklist, assembles the counter page's finished tooling, checks the tests themselves with mutation testing, walks a real change through the whole pipeline and ends with the review and what comes next.
The standard
Over the block, Gareth and Mira have agreed what every Food Hub project must have. Written as a checklist, it is the definition of done for the capstone.
| Area | Requirement | Lesson |
|---|---|---|
| Node.js | .nvmrc names one LTS version; engines states the supported range | 1, 2, 11 |
| Packages | package-lock.json committed; tools in devDependencies; npm ci in CI | 2 |
| Scripts | dev, build, lint, format, format:check, test, test:e2e | 2 |
| Build | tsc --noEmit then vite build; source maps; hashed file names | 3 |
| Lint | eslint.config.js with recommended rules and typescript-eslint; no warnings in CI | 4 |
| Format | Prettier with the shared .prettierrc; format on save; check in CI | 5 |
| Unit tests | Vitest; money in cents; edge cases; no test without an assertion | 6 |
| Doubles | Clock, network and storage injected or faked; mocks restored | 7 |
| DOM tests | Testing Library queries by role; user-event; no fixed waits | 8 |
| End to end | Playwright for the critical paths; Chromium and WebKit; traces on retry | 9 |
| Bug fixes | Every fix starts with a failing regression test | 10 |
| CI | Workflow for every push and pull request; required checks; Dependabot | 11 |
The checklist is also a tool. Mira writes a short script that reads a project's package.json and reports which parts of the standard are missing, so that the dashboard and riverside-data can be checked the same way.
function checkProject(pkg) {
const problems = [];
// Applications need the full set of scripts; libraries such as riverside-data need fewer.
const required = pkg.private ? ['dev', 'build', 'lint', 'format:check', 'test', 'test:e2e'] : ['build', 'lint', 'test'];
for (const name of required) {
if (!pkg.scripts?.[name]) problems.push(`missing script "${name}"`);
}
const tools = ['eslint', 'prettier', 'vitest', 'typescript', 'vite', '@playwright/test'];
for (const tool of tools) {
if (pkg.dependencies?.[tool]) problems.push(`${tool} should be a devDependency`);
}
if (!pkg.engines?.node) problems.push('engines.node is not set');
if (pkg.scripts?.lint && !pkg.scripts.lint.includes('eslint')) problems.push('lint does not run eslint');
return problems.length ? problems : ['meets the standard'];
}
const counterPage = {
name: 'counter-page', private: true, engines: { node: '>=24' },
scripts: { dev: 'vite', build: 'tsc --noEmit && vite build', lint: 'eslint .', format: 'prettier --write .', 'format:check': 'prettier --check .', test: 'vitest run', 'test:e2e': 'playwright test' },
devDependencies: { eslint: '^10.1.0', prettier: '^3.9.0', vitest: '^4.1.0' },
};
const dashboardBefore = {
name: 'office-dashboard', private: true,
scripts: { dev: 'vite', build: 'vite build', test: 'vitest run' },
dependencies: { 'riverside-data': '^2.3.0', vitest: '^4.1.0' },
};
for (const [name, pkg] of [['counter-page', counterPage], ['office-dashboard (before)', dashboardBefore]]) {
console.log(name + ':');
for (const p of checkProject(pkg)) console.log(' -', p);
}counter-page: - meets the standard office-dashboard (before): - missing script "lint" - missing script "format:check" - missing script "test:e2e" - vitest should be a devDependency - engines.node is not set
What this code does
checkProject compares a package.json with the standard: the scripts every application needs, tools placed in devDependencies, a supported Node.js range and a lint script that really runs ESLint. The counter page passes. The dashboard, before Mira works on it, is missing three scripts and the engines field and has vitest in the wrong dependency list.
The finished counter page
By the end of the first capstone session, the counter page's repository has the layout below. The application code is unchanged from before the block except for the bug fixes the tests found; everything new is tooling and tests.
{
"name": "counter-page",
"version": "1.6.0",
"private": true,
"type": "module",
"engines": { "node": ">=26" },
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"lint": "eslint .",
"format": "prettier --write .",
"format:check": "prettier --check .",
"test": "vitest run",
"test:watch": "vitest",
"test:e2e": "playwright test",
"check": "npm run lint && npm run format:check && npm test"
},
"dependencies": {
"riverside-data": "^2.3.0"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.65.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.9.0",
"@testing-library/user-event": "^14.6.0",
"eslint": "^10.1.0",
"globals": "^16.4.0",
"jsdom": "^27.0.0",
"prettier": "^3.9.0",
"typescript": "^7.0.0",
"typescript-eslint": "^8.46.0",
"vite": "^8.0.0",
"vitest": "^4.1.0"
}
}What this code does
The scripts follow the studio's naming, with a check script that runs the fast checks together before a push. The only runtime dependency is riverside-data; every tool is a devDependency. The version went to 1.6.0 because the block added features, such as the remove button and the error message for a failed order, without breaking anything.
Each range sets the lowest version the project accepts; the lock file records the exact versions installed, Dependabot proposes newer ones, and CI decides whether they are safe.
A complete suite in miniature
The counter page's real tests are spread across files, but their shape can be shown in one program. The next example brings together pieces from the whole block: a describe and test runner, money in cents, an EventTarget order, a fake storage and an injected clock for closing the day.
const results = { pass: 0, fail: 0 };
const describe = (name, fn) => { console.log(name); fn(); };
const test = (name, fn) => {
try { fn(); results.pass++; console.log(' \u2713', name); }
catch (e) { results.fail++; console.log(' \u2717', name, '-', e.message); }
};
const expect = (a) => ({ toBe: (b) => { if (!Object.is(a, b)) throw new Error(`expected ${b}, got ${a}`); } });
// Application code
const lineCents = (i) => { if (i.qty < 0) throw new RangeError('negative quantity'); return Math.round(i.price * 100) * i.qty; };
const orderTotal = (items, rate) => Math.round(items.reduce((s, i) => s + lineCents(i), 0) * (1 + rate)) / 100;
class Order extends EventTarget {
items = [];
add(item) { this.items.push(item); this.dispatchEvent(new Event('change')); }
}
function closeDay(orders, storage, now) {
const day = new Date(now).toISOString().slice(0, 10);
const cents = orders.reduce((s, o) => s + Math.round(o.total * 100), 0);
storage.set('tally:' + day, JSON.stringify({ orders: orders.length, cents }));
return day;
}
describe('orderTotal', () => {
test('empty order', () => expect(orderTotal([], 0.1)).toBe(0));
test('rounds 1.155 up to 1.16', () => expect(orderTotal([{ price: 0.35, qty: 3 }], 0.1)).toBe(1.16));
test('rejects a negative quantity', () => { try { lineCents({ price: 1, qty: -1 }); throw new Error('did not throw'); } catch (e) { expect(e.message).toBe('negative quantity'); } });
});
describe('Order', () => {
test('announces each change', () => {
const order = new Order(); let changes = 0;
order.addEventListener('change', () => changes++);
order.add({ price: 4.5, qty: 1 }); order.add({ price: 1.5, qty: 2 });
expect(changes).toBe(2);
});
});
describe('closeDay', () => {
test('saves the tally under the date of the injected clock', () => {
const storage = new Map();
const day = closeDay([{ total: 9.9 }, { total: 1.65 }], storage, Date.UTC(2027, 11, 18, 19, 30));
expect(storage.get('tally:' + day)).toBe('{"orders":2,"cents":1155}');
});
});
console.log(`\n${results.pass} passed, ${results.fail} failed`);orderTotal ✓ empty order ✓ rounds 1.155 up to 1.16 ✓ rejects a negative quantity Order ✓ announces each change closeDay ✓ saves the tally under the date of the injected clock 5 passed, 0 failed
What this code does
The program defines a tiny describe, test and expect, then a cut-down version of the counter page's order logic. Each describe block tests one unit: orderTotal with its rounding edge case and error, the Order object's change events, and closeDay with a Map as fake storage and a fixed time as the clock. Everything that would make the tests slow or unpredictable has been replaced, so all five run in a moment and give the same result every time.
// src/config.test.js: the real tax rate is configuration, so it gets its own small test.
const TAX_RATE = 0.13; // HST in Ontario
function lineCents(item) { return Math.round(item.price * 100) * item.qty; }
function orderTotal(items, taxRate) {
const subtotal = items.reduce((sum, item) => sum + lineCents(item), 0);
return Math.round(subtotal * (1 + taxRate)) / 100;
}
const checks = [
['tax rate is the one Rosa confirmed', TAX_RATE === 0.13],
['a typical lunch costs 11.87', orderTotal([{ price: 4.5, qty: 2 }, { price: 1.5, qty: 1 }], TAX_RATE) === 11.87],
['the rate is a fraction, not a percentage', TAX_RATE > 0 && TAX_RATE < 1],
];
for (const [name, ok] of checks) console.log(ok ? '\u2713' : '\u2717', name);✓ tax rate is the one Rosa confirmed ✓ a typical lunch costs 11.87 ✓ the rate is a fraction, not a percentage
What this code does
The unit tests in this course pass a round test rate, so their numbers are easy to check, and the real rate lives in one configuration file. This short test pins that value and checks one realistic order with it, so a mistyped rate fails CI rather than reaching the till. The last check catches the classic slip of writing the rate as a whole number.
Testing the tests: mutation testing
Lesson 6 warned that coverage shows what ran, not what was checked. A sharper question is: if the code had a bug, would a test fail? Mutation testing answers it directly. A tool makes small changes to the code, called mutants, such as turning < into <= or + into -, and runs the tests against each one. If a test fails, the mutant is killed; if every test still passes, the mutant survived, which means a bug of that kind would go unnoticed. Stryker is the usual mutation testing tool for JavaScript and TypeScript, and it works with Vitest.
const versions = {
original: (items, rate) => Math.round(items.reduce((s, i) => s + Math.round(i.price * 100) * i.qty, 0) * (1 + rate)) / 100,
'drop inner rounding': (items, rate) => Math.round(items.reduce((s, i) => s + i.price * 100 * i.qty, 0) * (1 + rate)) / 100,
'subtract tax': (items, rate) => Math.round(items.reduce((s, i) => s + Math.round(i.price * 100) * i.qty, 0) * (1 - rate)) / 100,
'floor instead of round': (items, rate) => Math.floor(items.reduce((s, i) => s + Math.round(i.price * 100) * i.qty, 0) * (1 + rate)) / 100,
'ignore quantity': (items, rate) => Math.round(items.reduce((s, i) => s + Math.round(i.price * 100), 0) * (1 + rate)) / 100,
};
const weakTests = [
[[], 0.1, 0],
[[{ price: 10, qty: 1 }], 0.1, 11],
];
const strongerTests = [
...weakTests,
[[{ price: 4.5, qty: 2 }, { price: 3, qty: 1 }], 0.1, 13.2],
[[{ price: 0.35, qty: 3 }], 0.1, 1.16],
];
const withAwkwardPrice = [...strongerTests, [[{ price: 1.15, qty: 3 }], 0.1, 3.8]];
function mutationReport(tests) {
const passes = (fn) => tests.every(([items, rate, want]) => fn(items, rate) === want);
const lines = [];
for (const [name, fn] of Object.entries(versions)) {
if (name === 'original') { lines.push(`original: ${passes(fn) ? 'all tests pass' : 'TESTS FAIL'}`); continue; }
lines.push(`${passes(fn) ? 'SURVIVED' : 'killed '} ${name}`);
}
return lines.join('\n');
}
console.log('With the first two tests:\n' + mutationReport(weakTests));
console.log('\nWith all four tests:\n' + mutationReport(strongerTests));
console.log('\nWith three items at 1.15 added:\n' + mutationReport(withAwkwardPrice));
console.log('\n1.15 * 100 =', 1.15 * 100);With the first two tests: original: all tests pass SURVIVED drop inner rounding killed subtract tax SURVIVED floor instead of round SURVIVED ignore quantity With all four tests: original: all tests pass SURVIVED drop inner rounding killed subtract tax killed floor instead of round killed ignore quantity With three items at 1.15 added: original: all tests pass killed drop inner rounding killed subtract tax killed floor instead of round killed ignore quantity 1.15 * 100 = 114.99999999999999
What this code does
Each mutant is a copy of orderTotal with one small, plausible bug. mutationReport runs a set of tests against the original, which must pass, and against every mutant, and reports whether some test catches it. With only an empty order and a single 10-dollar item, three of the four mutants survive. Adding the two-item order and the rounding case from Lesson 6 kills two more, but removing the rounding of each price to cents still survives until a test orders three items at 1.15, a price that is not a whole number of cents in floating point.
The last mutant is the instructive one. Every test Mira had written used prices whose cents happen to come out exactly, so the line that rounds each price to whole cents could be deleted without any test noticing, even though it is the very fix that Lesson 6 introduced. One more case, three items at 1.15, protects it: with the rounding the total is 3.80, and without it 3.79. Without mutation testing, that gap would have stayed hidden until a menu price change brought the bug back.
Mutation testing is slow, because it runs the tests once per mutant, so Brightwater runs Stryker weekly rather than on every push, and only on the code where mistakes are most costly: money, the overlap rule and the tally. A surviving mutant is a prompt to ask whether a test is missing, not a target to drive to zero.
A change through the whole pipeline
The second capstone session tests the setup with a real change. Rosa has asked for the receipt to show the number of items, so that the kitchen can check a bag at a glance. Mira works through it the way the block taught.
- Branch and test first. She creates a branch and writes a failing test for the receipt's new item count line, red.
- Code. She adds the line to receiptLines; the test passes, green. Format on save and ESLint in the editor keep the file tidy as she types.
- Refactor. She moves the counting into a small itemCount function with its own test, and the suite stays green.
- Check locally. npm run check runs lint, the format check and the unit tests in a few seconds.
- Push and open a pull request. CI runs the quality job, the tests on both Node.js versions and the end-to-end tests. All four checks pass in just under four minutes.
- Review. Gareth reads a diff of eleven lines, with no formatting noise, approves it, and the merge button turns green.
Then Gareth tries the other path on purpose. He opens a pull request that changes the receipt's total line to use the subtotal instead of the total, a plausible slip. The unit test for the receipt fails in the test job, the e2e job is skipped, and the pull request cannot be merged. The whole round trip, from push to a red check with the failing assertion in the log, takes under two minutes.
// Conventional commit messages decide the next version, as Lesson 2 described.
function nextVersion(current, commits) {
let [major, minor, patch] = current.split('.').map(Number);
const kinds = commits.map((c) => (/^\w+!:/.test(c) || c.includes('BREAKING CHANGE') ? 'major' : c.startsWith('feat') ? 'minor' : c.startsWith('fix') ? 'patch' : 'none'));
if (kinds.includes('major')) return `${major + 1}.0.0`;
if (kinds.includes('minor')) return `${major}.${minor + 1}.0`;
if (kinds.includes('patch')) return `${major}.${minor}.${patch + 1}`;
return current;
}
const sinceLastRelease = [
'test: add receipt item count case',
'feat: show item count on the receipt',
'refactor: extract itemCount',
'fix: keep the remove button hidden for an empty order',
'chore(deps): update vitest to 4.1.3',
];
console.log('counter-page 1.6.0 ->', nextVersion('1.6.0', sinceLastRelease));
console.log('only fixes ->', nextVersion('1.6.0', ['fix: total label spacing']));
console.log('only chores ->', nextVersion('1.6.0', ['chore: update README']));counter-page 1.6.0 -> 1.7.0 only fixes -> 1.6.1 only chores -> 1.6.0
What this code does
nextVersion reads each commit message's type: a feat raises the minor version, a fix the patch version, and an exclamation mark or BREAKING CHANGE the major version. The highest kind found wins, and commits such as tests, refactors and chores do not change the version. The receipt work therefore releases the counter page as 1.7.0.
The review
At the review on Friday, December 3, Gareth and Theo go through the checklist for all three projects. The counter page and riverside-data meet the standard. The dashboard meets all of it except end-to-end tests for its sign-in page, which wait on Theo's planned change to how staff sign in, so that item is recorded as a known gap with an issue in the repository rather than ticked off.
Theo's question is the one Gareth hoped for: what happens on the morning of the hamper drive if something breaks? Mira's answer is the reason for the whole block. A fix starts with a failing test that reproduces the problem. The editor formats and lints it. The tests run in seconds. CI checks the change on a clean machine in under five minutes. And because main is protected and always green, the release that goes to Rosa's tablet is one that has passed every check, not one that someone was sure was fine.
What comes next
The tools in this block will keep changing: there will be a Vite 9, an ESLint 11 and dozens of Playwright releases before the end of Mira's apprenticeship. Dependabot and CI make the updates routine, and the ideas underneath, static checks, layout handled by a machine, fast isolated tests, a few real browser tests and a pipeline that checks every change, will outlast all of them. The next block, planned for the new year, takes the same discipline to the server side, where Theo's API and Mira's JavaScript meet.
Common mistakes
MistakeA project is done when the tests pass.
InsteadCheck the tests themselves: they must fail for real bugs. Mutation testing and making each test fail once are ways to check.
MistakeMutation testing should run on every push.
InsteadIt runs the tests once per mutant, so run it on a schedule and on the most important code.
MistakeThe standard only applies to new projects.
InsteadApply it to old ones too, in small steps, and record any gap as an issue.
MistakeConfiguration values such as the tax rate do not need tests.
InsteadPin real configuration with a small test, because a mistyped value is a bug that reaches users.
Summary and key terms
- The capstone brings the counter page, riverside-data and the dashboard up to one standard: a named Node.js version, a committed lock file, consistent scripts, a checked and hashed build, ESLint with no warnings, Prettier, Vitest unit tests with money in cents, injected or faked dependencies, Testing Library DOM tests by role, Playwright tests for the critical paths, a failing regression test for every fix and a CI workflow with required checks and Dependabot.
- The standard can itself be checked by a script.
- Real configuration, such as the tax rate, gets a small test.
- Mutation testing changes the code in small ways and runs the tests against each mutant; surviving mutants show where tests are missing, and Stryker automates it.
- A change flows from a failing test, through code and refactoring, local checks, CI and review to a protected main branch.
- Conventional commit messages can decide the next semantic version.
- Tools will change; the practices last.
- definition of done
- The agreed list of conditions a piece of work must meet before it is finished.
- mutation testing
- Checking tests by making small changes to the code and seeing whether the tests fail.
- mutant
- A copy of the code with one small, deliberate change.
- killed mutant
- A mutant that at least one test catches.
- surviving mutant
- A mutant that every test still passes, showing a gap in the tests.
- Stryker
- A mutation testing tool for JavaScript and TypeScript.
- conventional commits
- A convention for commit messages, such as feat: and fix:, that tools can read.
- known gap
- A missing part of a standard recorded openly, with a plan, rather than hidden.
Practice problems
Work each problem on paper first, then reveal the answer to check.
A test suite has 100 coverage points out of 100, but a mutant that changes + to - survives. What does that mean?
Show answer
The code ran, but no test checks the result closely enough to notice the change.
Which tests killed the 'ignore quantity' mutant in this lesson?
Show answer
The two-item order with a quantity of 2, and the rounding case with a quantity of 3.
Why does the counter page have a separate test for its real tax rate?
Show answer
The other tests use a round test rate, so only this test would catch a mistyped real rate.
What version follows 1.6.0 after a feat commit and a fix commit?
Show answer
1.7.0.
Why is the dashboard's missing sign-in test recorded as an issue instead of ticked off?
Show answer
It is a known gap with a plan; hiding it would make the checklist untrustworthy.
Try it yourself
Find the missing scripts
Complete missingScripts(pkg, required) so that it returns the required script names that pkg.scripts does not define, in the order they appear in required.
A script whose command is an empty string counts as missing, and a package with no scripts field at all is missing every one.
function missingScripts(pkg, required) {
return [];
}
const required = ['dev', 'build', 'lint', 'format:check', 'test', 'test:e2e'];
console.log(missingScripts({ scripts: { dev: 'vite', build: 'vite build', test: 'vitest run', lint: '' } }, required));
console.log(missingScripts({ name: 'new-project' }, ['build', 'test']));
console.log(missingScripts({ scripts: Object.fromEntries(required.map((r) => [r, 'x'])) }, required));Try it yourself
Kill the surviving mutant
The tests for isLate(shift, now) from Lesson 7 pass against the correct code, but one mutant survives. Add one case to cases, as [now, expected], so that every mutant is killed.
Times are minutes since midnight and the shift starts at 690 (11:30). A volunteer who has not checked in is late only when it is more than 10 minutes after the start.
const correct = (s, now) => !s.checkedIn && now - s.start > 10;
const mutants = {
'>= instead of >': (s, now) => !s.checkedIn && now - s.start >= 10,
'ignores check-in': (s, now) => now - s.start > 10,
'> 1 instead of > 10': (s, now) => !s.checkedIn && now - s.start > 1,
};
const shift = { start: 690, checkedIn: false };
const cases = [
[690, false],
[720, true],
];
const passes = (fn) => cases.every(([now, want]) => fn(shift, now) === want) && fn({ ...shift, checkedIn: true }, 720) === false;
console.log('correct code passes:', passes(correct));
for (const [name, fn] of Object.entries(mutants)) console.log(passes(fn) ? 'SURVIVED' : 'killed', '-', name);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.