SyntaxPilot
Courses/JavaScript/Lesson 30
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript · Lesson 30 of 40

Testing with node:test

queued

These are the notes for JavaScript episode 30. Until now we checked every program by running it and looking at the output with our own eyes. A restaurant's billTotal prints 105, 32, 126, 0, it looks right, we ship it. Then a teammate changes one word, Math.round to Math.floor, the output becomes 105, 31, 126, 0, and nobody notices that customers are now charged wrongly. So you'll invent automated testing: write the right answer down once (an assertion, like a teacher's answer key), and let the computer compare every time. You'll use Node's built-in node:assert (silent when right, a loud AssertionError when wrong), then Node's built-in test runner node:test, which runs every test on its own and prints one report. You'll see why strictEqual fails on two identical-looking arrays (and deepStrictEqual passes), why assert.throws needs a function and not a call, why an async test without await compares Promise { <pending> }, and how real projects run everything with node --test and npm test. Every output below is real Node.js output (node main.js, Node 24). The timings in brackets, like (0.87ms), and duration_ms change on every run; yours will differ. For failing tests, the folder path is shortened to main.js, and the long list of at node:internal/... lines is sometimes cut, marked with ....

Builds on: == vs === (episode 3), functions and arrow functions (episode 9), reduce (11), spread (12), try/catch and error types like RangeError (13), modules and require/module.exports (18), rounding money with Math (20), regular expressions (23), async/await (27), async error handling (28), pure functions (29). Leads to: performance and memory (31).

The real-life idea: the teacher's answer key

A teacher has 500 exam papers to check. She doesn't solve every question again from scratch for each paper. She writes an answer key once, in advance. Then checking is just comparing: tick or cross. Paper 500 is checked exactly as carefully as paper 1, because the key never gets tired.

Checking exam papers Checking code
The student's answer (what was written) the actual value: what the function returned
The answer key, written once, in advance the expected value: the right answer, written in code
Comparing the answer with the key an assertion (assert.strictEqual(actual, expected))
A tick or a cross a test passes (✔) or fails (✖)
One question on the paper one test
The whole paper a test suite (a group of tests)
The checker going through all 500 papers the test runner (node:test)
The marks sheet at the end the summary: pass 2, fail 1

The problem: checking by eye

billTotal takes a list of items, adds price * qty for each one with reduce (episode 11: it walks through an array and builds up one value), adds 5% GST (Goods and Services Tax: multiply by 1.05), and rounds to whole rupees with Math.round:

function billTotal(items) {
  const sum = items.reduce((total, item) => total + item.price * item.qty, 0);
  return Math.round(sum * 1.05);
}
console.log(billTotal([{ price: 100, qty: 1 }]));
console.log(billTotal([{ price: 30, qty: 1 }]));
console.log(billTotal([{ price: 40, qty: 3 }]));
console.log(billTotal([]));
105
32
126
0

You check it in your head: Rs 30 plus 5% is Rs 31.50, which rounds to 32. Looks right. Ship it.

A month later a teammate changes one word, round to floor ("to avoid paise"). Math.floor always rounds down:

function billTotal(items) {
  const sum = items.reduce((total, item) => total + item.price * item.qty, 0);
  return Math.floor(sum * 1.05);
}
console.log(billTotal([{ price: 100, qty: 1 }]));
console.log(billTotal([{ price: 30, qty: 1 }]));
console.log(billTotal([{ price: 40, qty: 3 }]));
console.log(billTotal([]));
105
31
126
0

Did you spot it? 31, not 32. Most people don't. Every bill that ends in 50 paise is now wrong, and nobody notices for weeks.

Why? console.log only shows a value. It doesn't know what the right answer is. You are the test, and you must remember every right answer, every time. Eyes get tired. Computers don't.

A bug that comes back into code that used to work, like this one, is called a regression. Catching regressions automatically is the main job of tests.

assert: the answer key in code

Node has a built-in module (no install) called node:assert. You load it with require (episode 18). The node: prefix means "Node's own built-in module".

  • assert.strictEqual(actual, expected) compares the two values with === (strict equality: same type and same value).
  • If they are equal, it does nothing: silent when right.
  • If not, it throws an AssertionError: loud when wrong.

Our answer key: Rs 100 gives 105, Rs 30 gives 32, an empty cart gives 0. First with the correct Math.round:

const assert = require("node:assert");
function billTotal(items) {
  const sum = items.reduce((total, item) => total + item.price * item.qty, 0);
  return Math.round(sum * 1.05);
}
assert.strictEqual(billTotal([{ price: 100, qty: 1 }]), 105);
console.log("check 1 passed");
assert.strictEqual(billTotal([{ price: 30, qty: 1 }]), 32);
console.log("check 2 passed");
assert.strictEqual(billTotal([]), 0);
console.log("check 3 passed");
check 1 passed
check 2 passed
check 3 passed

Now the same checks against the buggy Math.floor version (only line 4 changes to return Math.floor(sum * 1.05);):

check 1 passed
node:assert:152
  throw new AssertionError(obj);
  ^

AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

31 !== 32

    at Object.<anonymous> (main.js:8:8)
    ...
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: 31,
  expected: 32,
  operator: 'strictEqual',
  diff: 'simple'
}

Node.js v24.22.2
  • The computer caught the bug instantly and told us what we got (actual: 31) and what we expected (expected: 32). 31 !== 32 reads "31 is not strictly equal to 32".
  • ERR_ASSERTION is the error's code, a fixed label you can search for. main.js:8:8 is line 8, column 8: the failing check.
  • But check 3 never ran. assert throws, and an uncaught error stops the whole script. With 50 checks you would fix one, run, find the next, run again. We want every check to run and one report at the end.

node:test: every test runs, one report

Node's built-in test runner is node:test. A test runner is a program that runs your tests, catches their failures and reports the results.

  • Call test("what the code should do", () => { ... }) with a name and a function that holds the assertions.
  • Each test runs on its own. If an assertion inside throws, the runner catches it, marks that one test as failed, and moves on.
  • At the end: ✔ or ✖ for every test, then a summary.
  • Name each test after what the code should do, so a failure reads like a sentence: "✖ rounds to the nearest rupee".
const test = require("node:test");
const assert = require("node:assert");
function billTotal(items) {
  const sum = items.reduce((total, item) => total + item.price * item.qty, 0);
  return Math.floor(sum * 1.05);
}
test("adds 5% GST", () => {
  assert.strictEqual(billTotal([{ price: 100, qty: 1 }]), 105);
});
test("rounds to the nearest rupee", () => {
  assert.strictEqual(billTotal([{ price: 30, qty: 1 }]), 32);
});
test("empty cart costs nothing", () => {
  assert.strictEqual(billTotal([]), 0);
});
✔ adds 5% GST (1.406694ms)
✖ rounds to the nearest rupee (0.958911ms)
✔ empty cart costs nothing (0.134399ms)
ℹ tests 3
ℹ suites 0
ℹ pass 2
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 9.880755

✖ failing tests:

test at main.js:10:1
✖ rounds to the nearest rupee (0.958911ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

  31 !== 32

      at TestContext.<anonymous> (main.js:11:10)
      ...
    generatedMessage: true,
    code: 'ERR_ASSERTION',
    actual: 31,
    expected: 32,
    operator: 'strictEqual',
    diff: 'simple'
  }
  • All three tests ran, even though the second failed. Summary: tests 3, pass 2, fail 1.
  • suites, cancelled, skipped and todo are explained further down. duration_ms is the total time.
  • Below the summary, the failing test with its line (main.js:10:1) and the same message, 31 !== 32. The name tells you what broke in plain English: it doesn't round to the nearest rupee.
  • When any test fails, node exits with exit code 1 (a number a program returns to the system when it ends: 0 means success, anything else means failure). That's how other tools know the tests failed.

Fix the code (Math.floor back to Math.round on line 5) and run the same tests:

✔ adds 5% GST (0.882087ms)
✔ rounds to the nearest rupee (0.151114ms)
✔ empty cart costs nothing (0.147746ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.328613

All green. If anyone ever changes that line again, these tests catch it in milliseconds. Green means safe to change. You just invented automated testing.

A unit test is a test of one small piece (a "unit") of code, usually one function, on its own. Every test in these notes is a unit test.

Comparing arrays and objects: deepStrictEqual

Test last episode's pure applyOffer (a pure function returns a new value and changes nothing outside itself). It returns a new array with 10% off every price:

const test = require("node:test");
const assert = require("node:assert");
const applyOffer = (prices) => prices.map((p) => p * 0.9);
test("10% off every price", () => {
  assert.strictEqual(applyOffer([100, 50]), [90, 45]);
});
✖ 10% off every price (1.464113ms)
ℹ tests 1
ℹ suites 0
ℹ pass 0
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.405888

✖ failing tests:

test at main.js:4:1
✖ 10% off every price (1.464113ms)
  AssertionError [ERR_ASSERTION]: Values have same structure but are not reference-equal:

  [
    90,
    45
  ]

      at TestContext.<anonymous> (main.js:5:10)
      ...
    generatedMessage: true,
    code: 'ERR_ASSERTION',
    actual: [Array],
    expected: [Array],
    operator: 'strictEqual',
    diff: 'simple'
  }

The arrays look the same: [90, 45]. But strictEqual uses ===, and for arrays and objects === asks: is it the very same array in memory? That is reference equality (a reference is the address of an object in memory; a variable holding an array really holds its address). applyOffer built one array and [90, 45] built another, so they are two different arrays, and === is false. That's what "same structure but not reference-equal" means.

Use assert.deepStrictEqual. It compares what's inside, item by item (and key by key for objects), strictly (=== for each item):

const test = require("node:test");
const assert = require("node:assert");
const applyOffer = (prices) => prices.map((p) => p * 0.9);
test("10% off every price", () => {
  assert.deepStrictEqual(applyOffer([100, 50]), [90, 45]);
});
✔ 10% off every price (1.326636ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 14.547189

Rule: strictEqual for numbers, strings and booleans; deepStrictEqual for arrays and objects.

Testing errors: assert.throws needs a function

Good code also refuses bad input. billTotal now throws a RangeError (the built-in error type for "a value outside the allowed range", episode 13) if a price is negative. Let's test that it really throws, with assert.throws:

const test = require("node:test");
const assert = require("node:assert");
function billTotal(items) {
  for (const item of items) {
    if (item.price < 0) throw new RangeError("Price cannot be negative");
  }
  const sum = items.reduce((total, item) => total + item.price * item.qty, 0);
  return Math.round(sum * 1.05);
}
test("rejects a negative price", () => {
  assert.throws(billTotal([{ price: -5, qty: 1 }]), RangeError);
});
✖ rejects a negative price (0.697868ms)
ℹ tests 1
ℹ suites 0
ℹ pass 0
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10.924221

✖ failing tests:

test at main.js:10:1
✖ rejects a negative price (0.697868ms)
  RangeError: Price cannot be negative
      at billTotal (main.js:5:31)
      at TestContext.<anonymous> (main.js:11:17)
      ...

It failed with exactly the error we wanted! Why? JavaScript works out the arguments first. billTotal([...]) is a call, so it ran right there in the brackets and threw before assert.throws even started. The error escaped the test. assert.throws needs a function it can call itself, inside its own try/catch. So wrap the call in an arrow function:

  assert.throws(() => billTotal([{ price: -5, qty: 1 }]), RangeError);
✔ rejects a negative price (1.543123ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 15.587445

assert.throws called our arrow function, saw a RangeError, and passed. The second argument can be an error class (RangeError), or an object of properties the error must have, like { name: "RangeError", message: "Price cannot be negative" }.

Testing async code: async, await and assert.rejects

pay (episodes 27 and 28) waits 100 ms, rejects a bill of zero, and otherwise returns a receipt. Two new names:

  • describe("name", fn) groups related tests under one name. A group is called a suite (that's the suites line in the summary).
  • it("name", fn) is just another name for test. Together they read like a sentence: "describe pay(): it pays a normal bill".
const { describe, it } = require("node:test");
const assert = require("node:assert");
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function pay(amount) {
  await wait(100);
  if (amount <= 0) throw new Error("Invalid amount");
  return { status: "paid", amount };
}
describe("pay()", () => {
  it("pays a normal bill", () => {
    const receipt = pay(180);
    assert.deepStrictEqual(receipt, { status: "paid", amount: 180 });
  });
});
▶ pay()
  ✖ pays a normal bill (6.476493ms)
✖ pay() (7.3144ms)
ℹ tests 1
ℹ suites 1
ℹ pass 0
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 132.124429

✖ failing tests:

test at main.js:10:3
✖ pays a normal bill (6.476493ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected

  + Promise {
  +   <pending>,
  +   Symbol(async_id_symbol): 52,
  +   Symbol(trigger_async_id_symbol): 16
  - {
  -   amount: 180,
  -   status: 'paid'
    }

      at TestContext.<anonymous> (main.js:12:12)
      ...
    generatedMessage: true,
    code: 'ERR_ASSERTION',
    actual: [Promise],
    expected: [Object],
    operator: 'deepStrictEqual',
    diff: 'simple'
  }
  • + actual - expected is a diff (a line-by-line comparison): lines with + are what we got, lines with - are what we expected.
  • The actual value is a Promise that is still <pending>: the missing-await trap from episode 27. An async function always returns a promise, and we compared the token, not the food.
  • The two Symbol(...) lines are Node's internal tracking numbers for that promise; the numbers change from run to run. Ignore them.

Make the test function async and await pay(180). For the zero bill use await assert.rejects(promise, expected), which checks that a promise rejects (fails) with that error:

const { describe, it } = require("node:test");
const assert = require("node:assert");
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function pay(amount) {
  await wait(100);
  if (amount <= 0) throw new Error("Invalid amount");
  return { status: "paid", amount };
}
describe("pay()", () => {
  it("pays a normal bill", async () => {
    const receipt = await pay(180);
    assert.deepStrictEqual(receipt, { status: "paid", amount: 180 });
  });
  it("rejects a zero bill", async () => {
    await assert.rejects(pay(0), { message: "Invalid amount" });
  });
});
▶ pay()
  ✔ pays a normal bill (106.261033ms)
  ✔ rejects a zero bill (101.170946ms)
✔ pay() (209.945007ms)
ℹ tests 2
ℹ suites 1
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 213.737414

The pay() suite with two ticks inside, each about 100 ms (the wait). The test runner waits for an async test to finish, as long as the test function returns the promise (an async function always does). assert.rejects itself returns a promise, so it needs await too (see Common mistakes).

Tests in a real project: bill.js + bill.test.js

In a real project the code lives in bill.js and its tests in bill.test.js, right next to it. The code file exports the function (episode 18):

// bill.js
function billTotal(items) {
  for (const item of items) {
    if (item.price < 0) throw new RangeError("Price cannot be negative");
  }
  const sum = items.reduce((total, item) => total + item.price * item.qty, 0);
  return Math.round(sum * 1.05);
}

module.exports = { billTotal };
// bill.test.js
const { describe, it } = require("node:test");
const assert = require("node:assert");
const { billTotal } = require("./bill.js");

describe("billTotal()", () => {
  it("adds 5% GST", () => {
    assert.strictEqual(billTotal([{ price: 100, qty: 1 }]), 105);
  });
  it("rounds to the nearest rupee", () => {
    assert.strictEqual(billTotal([{ price: 30, qty: 1 }]), 32);
  });
  it("multiplies price by quantity", () => {
    assert.strictEqual(billTotal([{ price: 40, qty: 3 }]), 126);
  });
  it("rejects a negative price", () => {
    assert.throws(() => billTotal([{ price: -5, qty: 1 }]), RangeError);
  });
});

Run node --test in the project folder. Node finds every test file (names like *.test.js, *-test.js, *_test.js, test-*.js, or files inside a test folder) and runs them all:

$ node --test
▶ billTotal()
  ✔ adds 5% GST (0.719107ms)
  ✔ rounds to the nearest rupee (0.170071ms)
  ✔ multiplies price by quantity (0.135646ms)
  ✔ rejects a negative price (5.21141ms)
✔ billTotal() (7.45101ms)
ℹ tests 4
ℹ suites 1
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 161.360099

Now play the teammate: change Math.round to Math.floor in bill.js and run node --test again. The test file didn't change, yet the regression is caught:

▶ billTotal()
  ✔ adds 5% GST (0.841128ms)
  ✖ rounds to the nearest rupee (0.979125ms)
  ✔ multiplies price by quantity (2.234766ms)
  ✔ rejects a negative price (0.437998ms)
✖ billTotal() (10.472018ms)
ℹ tests 4
ℹ suites 1
ℹ pass 3
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 340.66194

✖ failing tests:

test at bill.test.js:9:3
✖ rounds to the nearest rupee (0.979125ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

  31 !== 32

      at TestContext.<anonymous> (bill.test.js:10:12)
      ...

package.json and npm test

Put the command in package.json (the project's settings file) under scripts, with the special name test:

{
  "name": "restaurant-bill",
  "version": "1.0.0",
  "scripts": {
    "test": "node --test"
  }
}

Now the whole team types npm test (npm is the package manager that comes with Node; npm test runs the test script), before every commit (saving a version of the code in git):

$ npm test

> restaurant-bill@1.0.0 test
> node --test

▶ billTotal()
  ✔ adds 5% GST (0.984588ms)
  ✔ rounds to the nearest rupee (0.19126ms)
  ✔ multiplies price by quantity (0.137113ms)
  ✔ rejects a negative price (0.388861ms)
✔ billTotal() (3.226726ms)
ℹ tests 4
ℹ suites 1
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 251.979218

Many teams also run npm test automatically on a server for every change (CI, continuous integration). Because a failing run exits with code 1, the server can block broken code from being merged.

test.skip and test.todo

  • test.skip(name, fn): don't run this test for now (the feature isn't built yet, or the test is temporarily broken). It is counted under skipped.
  • test.todo(name): a reminder of a test you still need to write. Counted under todo, never fails the run.
const test = require("node:test");
const assert = require("node:assert");
const billTotal = (items) => Math.round(items.reduce((t, i) => t + i.price * i.qty, 0) * 1.05);
test("adds 5% GST", () => {
  assert.strictEqual(billTotal([{ price: 100, qty: 1 }]), 105);
});
test.skip("applies a coupon code", () => {
  assert.strictEqual(billTotal([{ price: 100, qty: 1 }], "DIWALI10"), 95);
});
test.todo("adds a service charge for tables of 6 or more");
✔ adds 5% GST (0.834161ms)
﹣ applies a coupon code (0.142034ms) # SKIP
✔ adds a service charge for tables of 6 or more (0.114705ms) # TODO
ℹ tests 3
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 1
ℹ todo 1
ℹ duration_ms 8.625941

The skipped test never ran (it would have failed: there is no coupon code yet). # SKIP and # TODO mark them. describe and it have .skip and .todo too.

assert.match: checking text with a pattern

Sometimes you don't know the exact text, only its shape. assert.match(string, regex) passes if the string matches the regular expression (episode 23: a pattern for text: \d+ means "one or more digits", $ means "end of the text", \$ means a real dollar sign). assert.doesNotMatch is the opposite. Here the receipt line has a bug: no space after Rs:

const test = require("node:test");
const assert = require("node:assert");
const receiptLine = (dish, amount) => `${dish} ........ Rs${amount}`;
test("ends with Rs, a space and the amount", () => {
  assert.match(receiptLine("Masala dosa", 63), /Rs \d+$/);
});
test("never shows a dollar sign", () => {
  assert.doesNotMatch(receiptLine("Idli", 42), /\$/);
});
✖ ends with Rs, a space and the amount (1.194514ms)
✔ never shows a dollar sign (0.217647ms)
ℹ tests 2
ℹ suites 0
ℹ pass 1
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 7.394972

✖ failing tests:

test at main.js:4:1
✖ ends with Rs, a space and the amount (1.194514ms)
  AssertionError [ERR_ASSERTION]: The input did not match the regular expression /Rs \d+$/. Input:

  'Masala dosa ........ Rs63'

      at TestContext.<anonymous> (main.js:5:10)
      ...

beforeEach: a fresh start for every test

Tests must not depend on each other: each one should pass even if run alone. beforeEach(fn) runs fn before every test in its describe, so each test gets fresh data. (There are also afterEach, before and after.) These are called hooks: functions the runner calls at set moments.

const { describe, it, beforeEach } = require("node:test");
const assert = require("node:assert");
describe("cart", () => {
  let cart;
  beforeEach(() => {
    cart = [];
    console.log("fresh empty cart");
  });
  it("starts empty", () => {
    assert.strictEqual(cart.length, 0);
  });
  it("can add a dish", () => {
    cart.push("chai");
    assert.deepStrictEqual(cart, ["chai"]);
  });
  it("is empty again for the next test", () => {
    assert.strictEqual(cart.length, 0);
  });
});
fresh empty cart
fresh empty cart
fresh empty cart
▶ cart
  ✔ starts empty (1.644716ms)
  ✔ can add a dish (0.841779ms)
  ✔ is empty again for the next test (0.32613ms)
✔ cart (4.023984ms)
ℹ tests 3
ℹ suites 1
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10.802563

beforeEach ran three times, so the chai pushed in test 2 was gone by test 3. (Your own console.log lines appear first because the runner prints its report after collecting the results.)

Write the test first: red, green, refactor (TDD)

Test-driven development (TDD) means writing the test before the code, in three steps:

  1. Red: write a test for what the code should do. It fails (✖).
  2. Green: write just enough code to make it pass (✔).
  3. Refactor: clean up or improve the code (refactoring = changing how code is written without changing what it does), staying green.

From the video: free delivery from Rs 500

The restaurant owner's new rule: orders of Rs 500 or more get free delivery, smaller orders pay Rs 40. Red: the tests come first, aimed exactly at the edge (500 and 499), before deliveryFee exists:

const test = require("node:test");
const assert = require("node:assert");
test("orders of 500 or more get free delivery", () => {
  assert.strictEqual(deliveryFee(500), 0);
});
test("smaller orders pay 40", () => {
  assert.strictEqual(deliveryFee(499), 40);
});
✖ orders of 500 or more get free delivery (0.836009ms)
✖ smaller orders pay 40 (0.150131ms)
ℹ tests 2
ℹ suites 0
ℹ pass 0
ℹ fail 2
...
✖ orders of 500 or more get free delivery (0.836009ms)
  ReferenceError: deliveryFee is not defined
...
✖ smaller orders pay 40 (0.150131ms)
  ReferenceError: deliveryFee is not defined

Green? A first attempt uses >:

function deliveryFee(total) {
  return total > 500 ? 0 : 40;
}
✖ orders of 500 or more get free delivery (1.896284ms)
✔ smaller orders pay 40 (0.428877ms)
ℹ tests 2
ℹ suites 0
ℹ pass 1
ℹ fail 1
...
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

  40 !== 0

total > 500 is false for exactly 500, an off-by-one bug (a mistake right at a boundary). The edge test caught it. With total >= 500 both tests pass:

✔ orders of 500 or more get free delivery (1.395919ms)
✔ smaller orders pay 40 (0.314546ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0

Always put tests at the edges of a rule (499, 500, 501), where off-by-one bugs live.

A longer walkthrough

Let's build splitBill(total, people). Red: the test first, with an empty function:

const test = require("node:test");
const assert = require("node:assert");
function splitBill(total, people) {}
test("splits Rs 1000 between 4 friends", () => {
  assert.strictEqual(splitBill(1000, 4), 250);
});
✖ splits Rs 1000 between 4 friends (1.581443ms)
...
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

  undefined !== 250

Green: the simplest code, return total / people;. The first test passes. Then red again: a new test for the next rule, "round each share up so the bill is fully paid":

const test = require("node:test");
const assert = require("node:assert");
function splitBill(total, people) {
  return total / people;
}
test("splits Rs 1000 between 4 friends", () => {
  assert.strictEqual(splitBill(1000, 4), 250);
});
test("rounds each share up so the bill is fully paid", () => {
  assert.strictEqual(splitBill(1000, 3), 334);
});
✔ splits Rs 1000 between 4 friends (93.02782ms)
✖ rounds each share up so the bill is fully paid (1.012731ms)
ℹ tests 2
ℹ suites 0
ℹ pass 1
ℹ fail 1
...
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
  + actual - expected

  + 333.3333333333333
  - 334

Green and refactor: Math.ceil (always rounds up), plus a guard for 0 people, with its own test:

const test = require("node:test");
const assert = require("node:assert");
function splitBill(total, people) {
  if (!Number.isInteger(people) || people < 1) {
    throw new RangeError("Need at least 1 person");
  }
  return Math.ceil(total / people);
}
test("splits Rs 1000 between 4 friends", () => {
  assert.strictEqual(splitBill(1000, 4), 250);
});
test("rounds each share up so the bill is fully paid", () => {
  assert.strictEqual(splitBill(1000, 3), 334);
});
test("refuses to split between 0 people", () => {
  assert.throws(() => splitBill(1000, 0), RangeError);
});
✔ splits Rs 1000 between 4 friends (0.899043ms)
✔ rounds each share up so the bill is fully paid (0.245567ms)
✔ refuses to split between 0 people (0.485627ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.927868

Writing the test first forces you to decide what "correct" means before you code, and you get a test for free. Notice which code was easiest to test today: pure functions (episode 29). Same input, same output, nothing hidden, so a test is just "call it, compare the result".

Common mistakes (and what really happens)

You wrote What happens Why Fix
console.log(billTotal(items)) 31 printed, nobody notices no expected value assert.strictEqual(actual, expected)
many plain assert lines in one script the first AssertionError stops the rest assert throws one check per test()
assert.strictEqual([90, 45], [90, 45]) Values have same structure but are not reference-equal === compares references assert.deepStrictEqual
assert.throws(billTotal(bad), RangeError) RangeError: Price cannot be negative (test fails) the call ran before throws started assert.throws(() => billTotal(bad), RangeError)
assert.throws(() => billTotal(bad), TypeError) The error is expected to be an instance of "TypeError". Received "RangeError" wrong error type expect the error the code really throws
assert.throws(() => billTotal(good), RangeError) Missing expected exception (RangeError). the function didn't throw at all good: the test caught a missing check
it("pays", () => { const r = pay(180); ... }) actual - expected diff showing + Promise { + <pending>, missing await async () => { const r = await pay(180); ... }
assert.rejects(pay(0), ...) without await ✔ is printed, then generated asynchronous activity after the test ended and exit code 1 the test ended before the promise was checked await assert.rejects(...)
assert.equal("105", 105) passes (no error) assert.equal is loose == always use strictEqual / deepStrictEqual
assert.strictEqual(0.1 + 0.2, 0.3) + 0.30000000000000004 - 0.3 floating-point maths (episode 20) compare rounded rupees or paise, e.g. Math.round(x * 100)
file named billtests.js, then node --test tests 0, nothing ran the name doesn't match a test pattern bill.test.js

The missing await on assert.rejects is sneaky. Real output for a test that expects the wrong message:

const test = require("node:test");
const assert = require("node:assert");
async function pay(amount) {
  if (amount <= 0) throw new Error("Invalid amount");
  return { status: "paid", amount };
}
test("rejects a zero bill", () => {
  assert.rejects(pay(0), { message: "Amount must be positive" });
});
✔ rejects a zero bill (2.198509ms)
ℹ Error: Test "rejects a zero bill" at main.js:7:1 generated asynchronous activity after the test ended. This activity created the error "AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected

  Comparison {
+   message: 'Invalid amount'
-   message: 'Amount must be positive'
  }
" and would have caused the test to fail, but instead triggered an unhandledRejection event.
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.602972

The summary says pass 1, but the run still exits with code 1. Always await assert.rejects.

Mini project: test the restaurant ordering code

Four small functions, pure where possible, and a suite for each: deepStrictEqual for carts, throws for bad input, beforeEach for a fresh cart, async + rejects for ordering.

const { describe, it, beforeEach } = require("node:test");
const assert = require("node:assert");

// ---- the code under test ----
const MENU = { chai: 20, samosa: 15, dosa: 60 };
const COUPONS = { FIRST50: 50, FEST10: 10 };

function addItem(cart, dish, qty = 1) {
  if (!(dish in MENU)) throw new Error(dish + " is not on the menu");
  return [...cart, { dish, price: MENU[dish], qty }];
}
function cartTotal(cart) {
  const sum = cart.reduce((total, line) => total + line.price * line.qty, 0);
  return Math.round(sum * 1.05);
}
function applyCoupon(total, code) {
  if (!(code in COUPONS)) throw new RangeError("Unknown coupon " + code);
  return Math.max(0, total - COUPONS[code]);
}
async function placeOrder(cart) {
  await new Promise((resolve) => setTimeout(resolve, 50));
  if (cart.length === 0) throw new Error("Cart is empty");
  return { token: 17, total: cartTotal(cart) };
}

// ---- the tests ----
describe("addItem()", () => {
  it("adds a line with the menu price", () => {
    assert.deepStrictEqual(addItem([], "dosa", 2), [{ dish: "dosa", price: 60, qty: 2 }]);
  });
  it("does not change the old cart", () => {
    const empty = [];
    addItem(empty, "chai");
    assert.deepStrictEqual(empty, []);
  });
  it("refuses a dish that is not on the menu", () => {
    assert.throws(() => addItem([], "pizza"), { message: "pizza is not on the menu" });
  });
});

describe("cartTotal() and applyCoupon()", () => {
  let cart;
  beforeEach(() => {
    cart = addItem(addItem([], "chai", 2), "samosa", 2);
  });
  it("adds 5% GST and rounds", () => {
    assert.strictEqual(cartTotal(cart), 74);
  });
  it("takes Rs 50 off with FIRST50", () => {
    assert.strictEqual(applyCoupon(cartTotal(cart), "FIRST50"), 24);
  });
  it("never goes below zero", () => {
    assert.strictEqual(applyCoupon(30, "FIRST50"), 0);
  });
  it("rejects an unknown coupon", () => {
    assert.throws(() => applyCoupon(100, "FREEFOOD"), RangeError);
  });
});

describe("placeOrder()", () => {
  it("returns a token and the total", async () => {
    const receipt = await placeOrder(addItem([], "dosa"));
    assert.deepStrictEqual(receipt, { token: 17, total: 63 });
  });
  it("rejects an empty cart", async () => {
    await assert.rejects(placeOrder([]), { message: "Cart is empty" });
  });
});
▶ addItem()
  ✔ adds a line with the menu price (1.417517ms)
  ✔ does not change the old cart (0.232455ms)
  ✔ refuses a dish that is not on the menu (1.007974ms)
✔ addItem() (5.980881ms)
▶ cartTotal() and applyCoupon()
  ✔ adds 5% GST and rounds (0.632539ms)
  ✔ takes Rs 50 off with FIRST50 (1.451769ms)
  ✔ never goes below zero (0.668249ms)
  ✔ rejects an unknown coupon (1.706211ms)
✔ cartTotal() and applyCoupon() (5.211739ms)
▶ placeOrder()
  ✔ returns a token and the total (50.678993ms)
  ✔ rejects an empty cart (50.873935ms)
✔ placeOrder() (102.440846ms)
ℹ tests 9
ℹ suites 3
ℹ pass 9
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 124.380672
  • 2 chai (40) + 2 samosa (30) = 70, plus 5% = 73.50, rounds to 74. Minus Rs 50 = 24.
  • "does not change the old cart" checks that addItem is pure: [...cart, ...] builds a new array (spread, episode 12).
  • Try breaking things: remove Math.max(0, ...), or the await inside placeOrder's test, and watch which test names turn red.

Practice

  1. Write at least 5 tests for billTotal, including a quantity of 0, several lines in one bill, and a second rounding case.
  2. Test applyOffer with deepStrictEqual, and also check that it doesn't change the original array and returns a new one.
  3. Make billTotal throw a RangeError for a negative quantity, and test the error's name and message.
  4. Write an async bookTable(people) that rejects above 8 people, and test both outcomes with await and assert.rejects.
Solutions

1 and 3 together:

const test = require("node:test");
const assert = require("node:assert");
function billTotal(items) {
  for (const item of items) {
    if (item.price < 0) throw new RangeError("Price cannot be negative");
    if (item.qty < 0) throw new RangeError("Quantity cannot be negative");
  }
  const sum = items.reduce((total, item) => total + item.price * item.qty, 0);
  return Math.round(sum * 1.05);
}
test("adds 5% GST", () => assert.strictEqual(billTotal([{ price: 100, qty: 1 }]), 105));
test("rounds 31.50 up to 32", () => assert.strictEqual(billTotal([{ price: 30, qty: 1 }]), 32));
test("rounds 10.50 up to 11", () => assert.strictEqual(billTotal([{ price: 10, qty: 1 }]), 11));
test("qty 0 costs nothing", () => assert.strictEqual(billTotal([{ price: 250, qty: 0 }]), 0));
test("adds several lines", () =>
  assert.strictEqual(billTotal([{ price: 20, qty: 2 }, { price: 60, qty: 1 }]), 105));
test("rejects a negative qty", () =>
  assert.throws(() => billTotal([{ price: 20, qty: -1 }]), { name: "RangeError", message: "Quantity cannot be negative" }));
✔ adds 5% GST (0.818272ms)
✔ rounds 31.50 up to 32 (0.138565ms)
✔ rounds 10.50 up to 11 (0.199361ms)
✔ qty 0 costs nothing (0.132643ms)
✔ adds several lines (0.13246ms)
✔ rejects a negative qty (0.663811ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10.614551

A one-line arrow function without braces returns the assertion's result; that's fine, the test only cares whether it throws.

2.

const test = require("node:test");
const assert = require("node:assert");
const applyOffer = (prices) => prices.map((p) => p * 0.9);
test("10% off every price", () => {
  assert.deepStrictEqual(applyOffer([100, 50, 200]), [90, 45, 180]);
});
test("does not change the original array", () => {
  const prices = [100, 50];
  applyOffer(prices);
  assert.deepStrictEqual(prices, [100, 50]);
});
test("returns a new array", () => {
  const prices = [100];
  assert.notStrictEqual(applyOffer(prices), prices);
});
✔ 10% off every price (1.400535ms)
✔ does not change the original array (0.180729ms)
✔ returns a new array (0.142769ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.486003

assert.notStrictEqual passes when !==: here, when the result is a different array from the input. That's reference equality used on purpose.

  1. Same shape as the pay() tests: async function bookTable(people) { await wait(100); if (people > 8) throw new RangeError("Max 8 people per table"); return { table: 4, people }; }, then test("books a table for 4", async () => { assert.deepStrictEqual(await bookTable(4), { table: 4, people: 4 }); }); and test("rejects 10 people", async () => { await assert.rejects(bookTable(10), { name: "RangeError", message: "Max 8 people per table" }); });. We ran it: ✔ books a table for 4, ✔ rejects 10 people, pass 2, each test about 100 ms.

Quick quiz

Pass or fail?

const test = require("node:test");
const assert = require("node:assert");
const a = { dish: "dosa" };
const b = { dish: "dosa" };
test("order", () => {
  assert.strictEqual(a, b);
});
  • A. Pass
  • B. Fail: not reference-equal
  • C. SyntaxError
  • D. Fail: "dosa" !== "dosa"
Answer

B. strictEqual compares with ===. a and b are two different objects in memory, so === is false even though they look the same. deepStrictEqual would pass. Real output:

✖ order (1.534602ms)
ℹ tests 1
ℹ suites 0
ℹ pass 0
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.663949

✖ failing tests:

test at main.js:5:1
✖ order (1.534602ms)
  AssertionError [ERR_ASSERTION]: Values have same structure but are not reference-equal:

  {
    dish: 'dosa'
  }

      at TestContext.<anonymous> (main.js:4:10)
      ...

Interview questions

  • Why write automated tests instead of checking console.log output? console.log has no expected value; a person must remember every right answer. Tests store the expected value once and check it every run, in milliseconds, catching regressions.
  • What is an assertion? A check that a condition holds (usually actual equals expected); it does nothing when true and throws an AssertionError when false.
  • strictEqual vs deepStrictEqual? strictEqual uses === (for objects that means the same reference). deepStrictEqual compares contents recursively, each item strictly.
  • Why is assert.equal discouraged? It uses loose ==, so "105" equals 105.
  • Why does assert.throws(fn(), Err) fail? fn() runs and throws while the arguments are being evaluated, before assert.throws can catch it. Pass a function: () => fn().
  • How do you test async code? Make the test function async, await the result, and use await assert.rejects(promise, expected) for failures. The runner waits for the returned promise.
  • What do describe and it do? describe groups tests into a suite; it is an alias for test.
  • What are hooks like beforeEach? Functions the runner calls before/after each test (or the whole suite) to set up fresh data, so tests don't depend on each other.
  • What is TDD? Test-driven development: write a failing test (red), the minimum code to pass (green), then refactor while staying green.
  • What is a regression, and how do tests help? A bug in code that used to work. A test that once passed starts failing, so it is caught immediately.
  • How does node --test find tests? By file name patterns such as *.test.js, *-test.js, *_test.js, test-*.js and files under test/.
  • Why are pure functions easy to test? Same input always gives the same output, with no hidden state or side effects, so a test is just call-and-compare.

Glossary

Term Meaning Example
Test a small piece of code that checks other code gives the right result test("adds 5% GST", ...)
Unit test a test of one small unit (usually one function) on its own the billTotal tests
Automated testing letting the computer run checks, instead of reading output by eye npm test
Assertion a check that throws if something isn't true assert.strictEqual(a, b)
Actual / expected what the code really returned / the right answer you wrote down actual: 31, expected: 32
node:assert Node's built-in module of assertion functions require("node:assert")
AssertionError the error an assertion throws when it fails; code ERR_ASSERTION 31 !== 32
assert.strictEqual passes if actual === expected numbers, strings
assert.deepStrictEqual passes if the contents are the same, item by item, strictly arrays, objects
assert.notStrictEqual passes if actual !== expected "returns a new array"
assert.equal the old loose == version; avoid "105" equals 105
assert.throws(fn, expected) calls fn and passes if it throws the expected error () => billTotal(bad)
assert.rejects(promise, expected) passes if the promise rejects with the expected error; must be awaited await assert.rejects(pay(0), ...)
assert.match / doesNotMatch passes if a string does / doesn't match a regular expression /Rs \d+$/
Regular expression a pattern for text \d+ = one or more digits
Reference the memory address an object variable really holds two [90, 45] arrays, two addresses
Reference equality "is it the very same object?" (=== on objects) strictEqual([1], [1]) fails
Test runner the program that runs tests, catches failures and reports node:test
node:test Node's built-in test runner module require("node:test")
test(name, fn) define one test test("order", ...)
Test suite a group of related tests describe("pay()", ...)
describe / it group tests into a suite / another name for test it("pays a normal bill", ...)
Pass / fail (✔ / ✖) the test's assertions all held / one threw pass 2, fail 1
test.skip / test.todo don't run this test now / a test still to write # SKIP, # TODO
Hook a function the runner calls at a set moment beforeEach, afterEach, before, after
Diff (+ actual - expected) a line-by-line comparison of what you got and what you expected + 333.3333333333333
Exit code the number a program returns when it ends: 0 = success, else failure failing tests exit with 1
node --test find every test file in the folder and run it bill.test.js
package.json scripts.test the command npm test runs "test": "node --test"
npm test run the project's test script before every commit
Commit a saved version of the code in git
CI (continuous integration) a server that runs the tests on every change blocks broken code
Bug code that gives a wrong result Math.floor instead of Math.round
Off-by-one bug a mistake right at a boundary, like > where >= was needed total > 500 charges delivery on exactly Rs 500
Regression a bug in something that used to work the teammate's one-word change
TDD (test-driven development) write the test first: red, green, refactor splitBill
Red / green / refactor failing test / just enough code to pass / clean up, still passing
Refactor change how code is written without changing what it does
Pure function same input, same output, changes nothing outside applyOffer
RangeError built-in error for a value outside the allowed range negative price
GST Goods and Services Tax, 5% on restaurant bills here sum * 1.05
Math.round / floor / ceil round to nearest / always down / always up 31.5 → 32 / 31 / 32
Promise <pending> a promise that hasn't finished yet the missing-await test

Summary

  • Checking console.log output by eye lets bugs slip by: console.log doesn't know the right answer.
  • An assertion stores the expected value: assert.strictEqual(actual, expected) is silent when right and throws AssertionError [ERR_ASSERTION] when wrong, but a plain script stops at the first failure.
  • node:test: test(name, fn) runs every test on its own and prints ✔/✖ plus a summary; name tests after what the code should do.
  • strictEqual uses === (references for objects); use deepStrictEqual for arrays and objects.
  • assert.throws(() => fn(), ErrorType) needs a function, not a call. Async tests need async + await, and await assert.rejects(...).
  • describe/it group tests; beforeEach gives each test fresh data; test.skip/test.todo park tests.
  • Real projects: bill.js + bill.test.js, node --test, "test": "node --test" and npm test. Write the test first (red, green, refactor), and keep functions pure so they're easy to test.

Next episode: Performance and memory. Your code is now correct; next we make it fast: measuring speed, finding slow loops, and the memory leak that slowly eats a server.