AI Hints
Home›JavaScript Tutorial›Practice Projects 3
JavaScript · Lesson 123 of 138

Practice: Unit Tests

Checking your code automatically.

⏱ 2 min read▶ Video at 2:27:34🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Practice: Unit Tests
From the video: Practice: Unit Tests
  • 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.

app.mjsjavascript
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"));
Output
✔ 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.

keyvalue
test(name, fn)one check
strictEqualsame value
deepStrictEqualsame contents
throwsexpects 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
Next up: Practice: Tabs — a classic component