Developer tools
Automated tests: test and expect
Code that checks code: it calls a function with known data and compares the answer with the expected one.
Why it exists
Checking by hand means clicking through the site after every change and trying to remember what should be where. It's slow, and people forget. A test writes the check down once, and then the machine repeats it in seconds, as often as you like, on every commit. That's why tests make changing code safe: if something breaks, a red test shows exactly what. Tests are also requirements nobody can "forget": "exactly 3000 ships for free" is written so it gets checked automatically. And as more code is written by AI, tests are what answers "but is it actually correct?"
Where it's used
- Functions with rules: discounts, taxes, password and email validation, shipping costs: anywhere an off-by-one bug costs money.
- CI: GitHub Actions and friends run
npm teston every commit and refuse to merge code with red tests. - Bug fixes: first you write a test that reproduces the bug (it's red), then fix the code (it turns green), and the bug can never sneak back unnoticed.
- Learning platforms themselves: Tasky checks every challenge with tests: it calls your function and compares the answer with the expected one.
Syntax
test("name of the behavior", () => {
const result = fn(data); // arrange and act
expect(result).toBe(expected); // assert
});
expect(x).toBe(y) // the same value (like Object.is)
expect(x).toEqual(y) // equal contents of arrays and objects
expect(() => f()).toThrow() // f throws an error
await expect(promise).rejects.toThrow() // the promise rejectsExamples
function expect(actual) {
return {
toBe(expected) {
if (!Object.is(actual, expected)) throw new Error(`expected ${expected}, got ${actual}`);
return "ok";
},
};
}
const applyDiscount = (price, percent) => price - (price * percent) / 100;
expect(applyDiscount(1000, 10)).toBe(900); // → "ok"[1, 2] === [1, 2]; // → false — two different arrays
Object.is([1, 2], [1, 2]); // → false — this is how toBe compares
JSON.stringify([1, 2]) === JSON.stringify([1, 2]); // → true — same contentstoEqual, not toBefunction throws(fn) {
try {
fn();
return false;
} catch {
return true;
}
}
function withdraw(balance, amount) {
if (amount > balance) throw new Error("Insufficient funds");
return balance - amount;
}
throws(() => withdraw(100, 500)); // → true
throws(() => withdraw(100, 50)); // → falsetoThrow works: it calls the function you pass inside try/catchconst report = [];
function test(name, fn) {
try {
fn();
report.push("✓ " + name);
} catch (error) {
report.push("✗ " + name + ": " + error.message);
}
}
function expect(actual) {
return {
toBe(expected) {
if (actual !== expected) throw new Error(`expected ${expected}, got ${actual}`);
},
};
}
const average = (numbers) => numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
test("average of two numbers", () => expect(average([2, 4])).toBe(3));
test("empty array gives zero", () => expect(average([])).toBe(0));
report; // → ["✓ average of two numbers", "✗ empty array gives zero: expected 0, got NaN"]Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Inside, it's simple. test(name, fn) remembers a function with a name. The runner calls each one in turn inside try/catch: if it finishes without an error, the test is green; if it throws, it's red, and the error message goes into the report. If the test function is async, the runner waits for its promise.
expect(actual) returns an object with checks, called matchers. Each matcher compares and, on a mismatch, throws an error with a readable message: expected 900, received 1100. toBe compares like Object.is, which for arrays and objects means comparing references, so for contents you need toEqual, which walks the structure recursively.
toThrow takes a function, not a result: it calls the function itself inside try/catch. If you write expect(f()), the error flies out before expect gets a chance to catch anything.
Real runners (Vitest, Jest) add finding *.test.js files, describe groups, parallel runs, watch mode and coverage reports, but the heart is the same.
Traps
How it differs from…
try...catchA runner is
try/catcharound every test, and a matcher isif (…) throw. You can check errors by hand withtry/catch, buttoThrowis shorter and also complains when there was no error.
When to pick something else
Don't test one-off scripts and throwaway prototypes. Don't check implementation details (which internal variable the function happens to use): such tests break on every refactor even though the behavior didn't change. And don't try to check "does it look nice" with expect: appearance is checked by eye or with screenshot tests.
Practice
Lessons where this appears
- Who checks the checkersTale · Chapter 27 · Testing
- Why don't green tests mean the code works?Why? · Chapter 27 · Testing
- Mutant huntWorkshop · Chapter 27 · Testing
- The case of the green testsInvestigation · Chapter 27 · Testing
- Tests for a passwordLab · Chapter 27 · Testing
- The Mutant KingBoss · Chapter 27 · Testing