Module 26: Debugging and Testing
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
- Node.js has a built-in test runner, so there's nothing to install. To test functions, first export them from
their file (modules are covered fully in Module 29). At the end of
calc.js:
module.exports = { lineTotal, subtotal, addTax };
- Then create
calc.test.js:
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);
});
- Run all tests with
node --test. It finds files ending in.test.jsand reports passes and failures. - Useful checks:
assert.equal(actual, expected)for single values;assert.deepEqual(actual, expected)for arrays and objects;-
assert.throws(() => ...)to check that bad input throws. -
Each test: arrange the input, act (call the function), assert the result.
- Popular test tools like Vitest and Jest work much the same way, with extra features. You'll use one later.
🖱️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.
