Practice: Unit Tests
Checking your code automatically.
How do you know your code still works after you change it? You could check by hand every time. Or you could write tests, small programs that check your code for you, in a second. Node comes with everything you need.

- Does it still work?
- Checking by hand is slow
- Tests check for you
Testing with assert
We import assert from node assert. Test is a tiny helper that runs a check, and prints a tick if it passes, or a cross if it fails. Strict equal checks that two values are the same. Deep strict equal compares arrays and objects by their contents. And throws checks that bad input throws an error. The last test fails, because slugify turns two spaces into two dashes. That's exactly the kind of bug tests catch. Run it.
import assert from "node:assert/strict";
function test(name, fn) {
try { fn(); console.log("✔", name); }
catch (e) { console.log("✘", name); }
}
const slugify = (s) => s.trim().toLowerCase().replaceAll(" ", "-");
const unique = (arr) => [...new Set(arr)];
const safeDivide = (a, b) => { if (b === 0) throw new Error("zero"); return a / b; };
test("slugify makes URL slugs", () =>
assert.strictEqual(slugify(" Hello World "), "hello-world"));
test("unique removes duplicates", () =>
assert.deepStrictEqual(unique([1, 1, 2, 3, 3]), [1, 2, 3]));
test("safeDivide refuses zero", () => assert.throws(() => safeDivide(1, 0)));
test("slugify handles double spaces", () =>
assert.strictEqual(slugify("a b"), "a-b"));✔ slugify makes URL slugs ✔ unique removes duplicates ✔ safeDivide refuses zero ✘ slugify handles double spaces
Why tests matter
Tests catch bugs the moment you introduce them. They let you change code without fear, because they'll tell you if something breaks. Good tests are small, have clear names, and test one thing each. Node's built in test runner, node dash dash test, gives you a real test function, and libraries like Jest and Vitest work the same way.
| key | value |
|---|---|
| test(name, fn) | one check |
| strictEqual | same value |
| deepStrictEqual | same contents |
| throws | expects an error |
Summary
Tests check your code automatically. Assert, and a test runner, are all you need to start. Next, a tabs component on a page.
Key takeaways- node:assert
- strictEqual, throws
- Small, named tests