Module 26: Debugging and Testing

Lesson 4 of 5 · 15–25 minutes

Writing tests with Node's test runner

🏠The everyday picture

A teacher's answer key: for each question, the expected answer. The test runner marks each answer right or wrong and gives you the score.

📘What it really is

module.exports = { lineTotal, subtotal, addTax };
const test = require("node:test");
const assert = require("node:assert/strict");
const { lineTotal, subtotal } = require("./calc.js");

test("lineTotal multiplies price by quantity", () => {
  assert.equal(lineTotal(6000, 2), 12000);
});

test("lineTotal rejects a zero quantity", () => {
  assert.throws(() => lineTotal(6000, 0));
});

test("subtotal of an empty cart is 0", () => {
  assert.equal(subtotal([]), 0);
});

🖱️Try it

Write tests for every function in calc.js, using the cases you listed in Lesson 3. Run node --test. Then deliberately break one function (change a * to a +) and run the tests again. Watch them catch it. Undo the break.

✅Quick check

Why use assert.deepEqual instead of assert.equal for arrays?

Show the answer

equal checks whether two arrays are the same object; deepEqual checks whether their contents match.

All your tests pass. Does that prove the code is correct?

Show the answer

No. It proves it's correct for the cases tested. Good tests cover normal, edge and bad inputs.

← PreviousWhy automated tests matter
ProLearners Assist