Skip to the content.

Lesson 9: Test Your App with Node

Course home Previous: Lesson 8 Next: Lesson 10

Time: about 75 minutes.

Goals

By the end of this lesson you will be able to:

Concepts

Why tests matter more when an AI writes code

An agent can change ten files in a minute. You cannot click through every feature after every change. Tests are a checklist the computer runs for you in under a second, every time. They catch regressions: things that used to work and quietly broke.

Tests also act as a precise spec. “Streak counts through yesterday” is ambiguous; a test with real dates is not.

Node’s built-in test runner

Node.js 22 includes a test runner and assertion library. You need no packages. See the official test runner docs and assert docs.

import { test } from "node:test";
import assert from "node:assert/strict";
import { normalizeName } from "../habits.js";

test("normalizeName trims and collapses spaces", () => {
  assert.equal(normalizeName("   Drink   water  "), "Drink water");
});

Running node --test in a folder finds files with names like *.test.js (and a few other patterns) and runs them. For ES module import syntax in .js files, your folder needs a package.json with "type": "module".

What makes a good test case

For each function, test:

  1. The normal case. Typical input, typical output.
  2. The empty case. Empty string, empty list, nothing ticked.
  3. Boundaries. Exactly 60 characters vs 61; the last day of a month; a leap year.
  4. Bad input. null, wrong formats, a date that does not exist like 2026-02-30.
  5. The tricky real-world case. For dates: daylight saving changes. For names: duplicates with different capitals.

Pure functions are easy to test

Because habits.js and storage.js do not touch the page, tests can call them directly. That is the payoff for the split you made in Lesson 6. For storage.js, the tests pass in a fake storage object that behaves like localStorage, including one that throws to simulate blocked storage.

Walkthrough

Step 1: Set up

In your project root, create package.json if you do not have one:

{
  "name": "tiny-habits",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node --test"
  }
}

Create a tests/ folder. Commit.

Step 2: Write your first test by hand

Yes, by hand. Create tests/habits.test.js:

import { test } from "node:test";
import assert from "node:assert/strict";
import { normalizeName, validateName } from "../habits.js";

test("normalizeName trims and collapses spaces", () => {
  assert.equal(normalizeName("   Drink   water  "), "Drink water");
});

test("validateName rejects an empty name", () => {
  assert.equal(validateName("   ").ok, false);
});

Run:

node --test

You should see something like # pass 2 and # fail 0. Now break it on purpose: change "Drink water" to "Drink water" (two spaces) and run again. Read the failure output: it shows the expected and actual values. Undo your change.

Step 3: Ask the agent for edge-case tests

Read habits.js and tests/habits.test.js. Add tests using node:test and
node:assert/strict for:
- isDayKey: real dates, a leap day in a leap year and a non-leap year,
  month 13, missing zero padding, a number, null
- addDays: across a month end, a year end, and across the US daylight
  saving dates in 2026 (March 8 and November 1)
- toggleDay: checking then unchecking, sorted order, and that the original
  habit is not mutated
- currentStreak: today ticked, today not ticked yet, a gap yesterday,
  across a month boundary
Group them with describe. Do NOT change habits.js. If a test fails, stop
and tell me which one and why, instead of changing the code or the test.
Run node --test and show me the output.

The last instruction matters. An agent that sees a failing test may “fix” it by changing the expected value. Tests are your spec; the code must meet them, not the other way around.

Step 4: Review the tests themselves

Tests can be wrong too. For each new test, check:

Try mutation testing by hand: change addDays(today, -1) to addDays(today, -2) in currentStreak, run the tests, confirm something fails, then undo with git restore habits.js.

Step 5: Test storage with a fake

Add tests/storage.test.js. Create a small fakeStorage() helper backed by a
Map with getItem and setItem. Test:
- serialize then deserialize returns the same habits
- deserialize returns [] for null, "", invalid JSON and a JSON string
- a bare array still loads
- invalid entries (blank name, missing id, non-objects, duplicate ids) are
  dropped
- saveHabits then loadHabits through fakeStorage round-trips
- a storage object whose getItem and setItem throw gives [] on load and
  false on save
Do not change storage.js. Run node --test and show me the output.

Step 6: Test-first: let a test drive a new feature

Write this failing test yourself:

import { longestStreak } from "../habits.js";

test("longestStreak finds the best run", () => {
  const habit = {
    id: "h", name: "Read", createdAt: "2026-11-01",
    done: ["2026-11-01", "2026-11-02", "2026-11-05", "2026-11-06", "2026-11-07"],
  };
  assert.equal(longestStreak(habit), 3);
});

Run it: it fails because longestStreak does not exist (or your Lesson 6 version is wrong). Then:

tests/habits.test.js has a failing test for longestStreak. Implement
longestStreak in habits.js to make it pass. Do not change the test. Run
node --test and show me the output.

This is the most reliable way to work with agents: you write the expectation, the agent writes the code.

Step 7: Make tests part of every change

Add to AGENTS.md:

- After any change, run `node --test`. All tests must pass before you say you're done.
- Never delete, skip or loosen a test to make it pass. If a test seems wrong, stop and ask me.

Commit everything:

git add -A
git commit -m "Add node:test suite for habits and storage"

Step 8: Compare with the reference

Run the reference suite:

cd ../path/to/this/repo/project
node --test

It has 31 tests across 8 groups. Read project/tests/habits.test.js and project/tests/storage.test.js. Find one case they test that you did not, and add it to yours.

What good output looks like

Checklist

Mini-quiz

  1. What does node --test do?
  2. What is a regression?
  3. Why test addDays("2026-03-07", 1) specifically?
  4. A test fails after the agent’s change, and the agent edits the test’s expected value so it passes. What is wrong with that?
  5. Why can storage.js be tested without a browser?
  6. What is the point of breaking the code on purpose and running the tests?
Answers 1. It finds test files (such as `*.test.js`) in the folder and runs them with Node's built-in test runner, reporting passes and failures. 2. Something that used to work and is now broken because of a change. 3. Daylight saving begins in the US on 8 March 2026. Naive date maths using local time and fixed 24-hour steps can skip or repeat a day around that date. 4. The test is the spec. Changing the expectation hides the bug instead of fixing it. The code should change, unless you decide the spec itself was wrong. 5. Its functions take the storage object as a parameter, so tests can pass in a fake that behaves like `localStorage`. 6. To prove the tests can actually fail. A test that passes no matter what protects nothing.

Assignment

  1. Write a test-first spec for completionRate(habit, today, windowDays): three ticks in the last seven days should give 43. Include windowDays = 0. Let the agent implement it.
  2. Add a test that a habit name containing HTML is stored as plain text by sanitizeHabit.
  3. Ask the agent: “Which important behaviour in this project has no test?” Add a test for the best answer.

Next: Lesson 10: Debug with AI