Who checks the checkers
What a test is, expect and its matchers, edge cases, toThrow, kinds of tests and TDD.
A test is code that calls other code and checks the result. Every test has three steps:
- arrange: the data we work with;
- act: call the function under test;
- assert: compare the answer with the expected one. If they differ, the test throws an error.
function expect(actual) {
return {
toBe(expected) {
if (actual !== expected) throw new Error(`expected ${expected}, got ${actual}`);
console.log("✓", actual, "===", expected);
},
};
}
function applyDiscount(price, percent) {
return price - (price * percent) / 100;
}
const price = 1000; // arrange
const result = applyDiscount(price, 10); // act
expect(result).toBe(900); // assertexpect in real libraries works the same way: an object full of checks, called matchers.toBe compares like ===. That's right for numbers and strings, but arrays and objects are compared by reference that way: two arrays that look the same are different arrays. For contents there's toEqual: it walks the structure and compares the items.
const cart = ["milk", "fish"];
console.log(cart === ["milk", "fish"]);
console.log(JSON.stringify(cart) === JSON.stringify(["milk", "fish"]));toBe; the second is a rough toEqual.Checks are wrapped in named tests: test("name", () => { … }). The test runner calls each one inside try/catch: no error means green, an error means red, and the name goes into the report. Let's build a runner in ten lines:
function test(name, fn) {
try {
fn();
console.log("✓", name);
} catch (error) {
console.log("✗", name, "—", error.message);
}
}
function expect(actual) {
return {
toBe(expected) {
if (actual !== expected) throw new Error(`expected ${expected}, got ${actual}`);
},
};
}
function average(numbers) {
let sum = 0;
for (const n of numbers) sum += n;
return sum / numbers.length;
}
test("average of two numbers", () => expect(average([2, 4])).toBe(3));
test("empty array gives zero", () => expect(average([])).toBe(0));NaN.Errors get tested too. If a function must throw on bad data, you write expect(() => withdraw(100, 500)).toThrow(). Notice the arrow: toThrow receives a function and calls it itself inside try/catch. Without the arrow, withdraw throws before expect gets a chance to catch anything, and the test fails even on correct code.
function withdraw(balance, amount) {
if (amount > balance) throw new Error("Not enough points");
return balance - amount;
}
function expectToThrow(fn) {
try {
fn();
} catch (error) {
console.log("✓ caught the error:", error.message);
return;
}
throw new Error("expected an error, but there was none");
}
expectToThrow(() => withdraw(100, 500));toThrow works inside.Good habits:
- one behavior per test: when a test fails, you know right away what broke;
- the name is a requirement: "empty array gives zero", "exactly 3000 ships free". The list of names reads like documentation;
- async code is awaited:
test("total", async () => { expect(await loadTotal()).toBe(420); }). Without await you compare a promise with a number.
In real projects tests live in files like cart.test.js next to cart.js, and a runner, Vitest or Jest, runs them with npm test. Tests come in three sizes:
- unit tests: one function, thousands of them in seconds;
- integration tests: several parts together, say a function and a database;
- end-to-end (e2e): a robot opens a real browser and clicks buttons (Playwright, Cypress). The most convincing and the slowest.
And in TDD (test-driven development) the test comes before the code: red (the test doesn't pass yet) → green (the minimum code to make it pass) → refactor (make the code nice while the tests stand guard).
>= for >, drop a line… Broken versions like these are called mutants. A good test suite is green on correct code and red on every mutant. In the workshop, we go hunting.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.