Your First Tests with node --test
A test is a few lines of code that run your code and check its answer, and Node's built-in test runner, node --test, runs every test file and reports what passed and what didn't.
Apprentice · Node.js · Unit Testing · Updated
After this lesson you can
- Write a test with test and assert from node:test and node:assert/strict, and run it with node --test
- Write a failing test first, then cover a rule's edge cases, such as the values on each side of a limit
- Check objects, thrown errors and rejected promises with assert.deepEqual, assert.throws and assert.rejects
Key takeaways
- A test runs a piece of your code and compares its answer with the one you expect, so after every change one command tells you what still works.
- test from node:test names a check, and assert.equal from node:assert/strict compares two values with ===, failing the test when they differ.
- node --test runs every file whose name ends in .test.js, and node --test --watch runs them again each time you save.
- Writing the test first and watching it fail proves the test can fail. Then test the edges, such as 5 and 6 when a rule changes at 6.
- assert.deepEqual compares objects by what they hold, assert.throws checks that a function throws, and assert.rejects checks that a promise rejects.
On the job, a change isn't finished until the tests pass, and a code review often starts with "where's the test?" Tests are also how you change code that already works without breaking it, in the APIs you build next and in every project after.
This chapter's example is Starlight Stage, a small concert venue that sells its tickets through an API. Before the API comes the one function every ticket sale runs: the price.
Checking by hand doesn't last
Starlight Stage charges the ticket price times the number of tickets, plus a $2 fee for each order, and sells 1 to 8 tickets at a time. In tickets.js:
export function orderTotal(price, quantity) {
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 8) {
throw new RangeError("Buy from 1 to 8 tickets at a time.");
}
return price * quantity + 2;
}
To check it, you could print orderTotal(25, 4), see 102, and compare it with the number in your head. That works once. But every time anyone changes the file, someone has to print it again and remember what the right answer was, and nobody does that for every function, every day.
A smoke alarm doesn't need you to sniff every room every hour: it checks all the time, and only makes noise when something's wrong. A test does that for code: a few lines that run your code and compare its answer with the one you expect. That comparison is an assertion, and a test runner is the program that runs every test and reports which passed. Node has one built in.
A first test file
Next to tickets.js, in a project whose package.json holds { "type": "module" }, make tickets.test.js:
import { test } from "node:test";
import assert from "node:assert/strict";
import { orderTotal } from "./tickets.js";
test("4 tickets at $25 cost $102, with the $2 order fee", () => {
assert.equal(orderTotal(25, 4), 102);
});
test takes a name and a function to run. assert.equal(actual, expected) compares the two with === (read "strictly equal") and fails the test when they differ. The strict in node:assert/strict makes every check strict, so the text "102" never passes for the number 102.
In VS Code's terminal, in the project folder, run it:
node --test
✔ 4 tickets at $25 cost $102, with the $2 order fee (0.5138ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 60.3945
node --test finds every file whose name ends in .test.js and runs it. Your times will differ.
Now say someone changes the fee to $3 by mistake. The same command catches it before a single fan pays too much. The report starts like this:
✖ 4 tickets at $25 cost $102, with the $2 order fee (0.9062ms)
ℹ tests 1
ℹ suites 0
ℹ pass 0
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 61.2555
✖ failing tests:
test at tickets.test.js:5:1
✖ 4 tickets at $25 cost $102, with the $2 order fee (0.9062ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
103 !== 102
103 !== 102 (read "103 is not strictly equal to 102") means the code gave 103 and the test expected 102. Under it, Node names the line in the test file where it happened. A name that says what the test checks, values included, tells you what broke before you open a file.
Test first, at the edges
Starlight Stage adds a rule: an order of 6 or more tickets pays no fee. This time, write the tests before the code. A rule that changes at 6 has two edge cases, the values right at the line: 5 still pays the fee, and 6 doesn't.
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { orderTotal } from "./tickets.js";
describe("orderTotal", () => {
it("4 tickets at $25 cost $102, with the $2 order fee", () => {
assert.equal(orderTotal(25, 4), 102);
});
it("5 tickets at $25 cost $127, still with the fee", () => {
assert.equal(orderTotal(25, 5), 127);
});
it("6 tickets at $25 cost $150, with no fee", () => {
assert.equal(orderTotal(25, 6), 150);
});
});
describe groups tests under one name, and it is another name for test that reads well inside it. Run them before you touch tickets.js:
▶ orderTotal
✔ 4 tickets at $25 cost $102, with the $2 order fee (0.4142ms)
✔ 5 tickets at $25 cost $127, still with the fee (0.5435ms)
✖ 6 tickets at $25 cost $150, with no fee (0.6307ms)
✖ orderTotal (2.2697ms)
Further down, the report says 152 !== 150. The red test is good news: it proves the test can fail, and it fails for the reason you expect, because the rule isn't written yet. Now change the end of orderTotal:
let fee = 2;
if (quantity >= 6) {
fee = 0;
}
return price * quantity + fee;
>= is read "greater than or equal to". Run the tests again, and all three pass. Writing the failing test first, then the code that makes it pass, is called test-driven development. While you work, node --test --watch stays running and runs the tests again each time you save a file. Stop it with Ctrl+C.
Objects, errors and waiting
Three more checks cover most of what you'll test. tickets.js gains two functions: receipt builds an object, and loadShows reads the venue's shows from a file, so it returns a promise:
import { readFile } from "node:fs/promises";
export function receipt(show, quantity) {
return { show: show.title, quantity, total: orderTotal(show.price, quantity) };
}
export async function loadShows(file) {
const text = await readFile(file, "utf8");
return JSON.parse(text);
}
import { test } from "node:test";
import assert from "node:assert/strict";
import { orderTotal, receipt, loadShows } from "./tickets.js";
test("a receipt for 2 Velvet Owls tickets says $52", () => {
const show = { title: "The Velvet Owls", price: 25 };
assert.deepEqual(receipt(show, 2), { show: "The Velvet Owls", quantity: 2, total: 52 });
});
test("9 tickets is too many: orderTotal throws a RangeError", () => {
assert.throws(() => orderTotal(25, 9), RangeError);
});
test("loading a shows file that isn't there rejects with ENOENT", async () => {
await assert.rejects(loadShows("no-such-file.json"), { code: "ENOENT" });
});
✔ a receipt for 2 Velvet Owls tickets says $52 (0.8758ms)
✔ 9 tickets is too many: orderTotal throws a RangeError (0.2771ms)
✔ loading a shows file that isn't there rejects with ENOENT (2.5861ms)
assert.deepEqualcompares objects and arrays by what they hold.assert.equalfails on two separate objects, even with the same values inside, because two separate objects are never===.assert.throwstakes a function to call. The arrow,() =>(read "arrow"), wraps the call, soassert.throwscan make it and catch the error. Without the arrow,orderTotal(25, 9)would throw beforeassert.throwsstarted, and the test would fail with theRangeErroritself.assert.rejectstakes a promise, and the testawaits it, so the test function isasync.{ code: "ENOENT" }checks the error's code, Node's code for "no such file".
Check yourself
2 questions to try on the lesson page.
So what
One command now tells you whether the venue's prices still work after any change, and the next lesson points the same test runner at a whole API.