javascript · level 3 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A catches every failure and reports the score.
With one assertion after another, the first failure stops everything, and you never hear about the rest. A test runner wraps each test in its own try...catch, records a pass or a fail with the reason, and carries on.
Here test takes a name and a function. A group of tests like this is a . Run the suite after every change: if an old test suddenly fails, you have caught a before your users do.
const score = { passed: 0, failed: 0 };
function test(name, check) {
try {
if (check() !== true) { throw new Error("returned false"); }
score.passed++;
} catch (error) {
score.failed++;
console.log(`FAIL ${name} (${error.name})`);
}
}
const shout = (text) => `${text.toUpperCase()}!`;
test("adds a bang", () => shout("hi") === "HI!");
test("copes with no text", () => shout() === "!");
console.log(`${score.passed} passed, ${score.failed} failed`); Real runners such as Jest and Vitest work the same way, with far more helpers.
guess first
One test crashes in the middle. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function test(name, check) {
try {
check();
console.log(`PASS ${name}`);
} catch (error) {
console.log(`FAIL ${name}: ${error.name}`);
}
}
const firstLetter = (word) => word[0].toUpperCase();
test("cat", () => { if (firstLetter("cat") !== "C") { throw new Error("wrong"); } });
test("empty word", () => { if (firstLetter("") !== "") { throw new Error("wrong"); } });
test("dog", () => { if (firstLetter("dog") !== "D") { throw new Error("wrong"); } });
console.log("all tests ran");
your turn
Your turn. Add a test to the suite.
Give the second test a name and pick an odd number, so the whole suite passes.
fix it
One crash hides the last test. Can you fix it?
- After the crash, did the empty list test run at all?
- The
trywraps the whole loop, so one crash ends every test after it. - Move
tryand itscatchinside the loop, around theifline, and log${name} crashedin thecatch.
nailed it
you built your own test runner. :D
- A test runner contains each failure and keeps going.
- A test suite guards your code against regressions.
- Run the suite after every change you make.
new words in your collection
- test runner
- test suite
- regression
This lesson isn’t saved. A free account remembers every lesson you finish.