Testing with the Node.js test runner
- Version
- 24
- Since
- 16.17.0
- Review
- Draft
Summary#
Register a named test with test(name, fn) from node:test and use assertions to check its result. The runner records a failure if the function throws or its returned promise rejects.
Syntax#
node --test loading-bay.test.mjs
Pass a file path to run that file. With no path, the runner discovers test files by name, including files ending in .test.mjs.
Example#
Save as loading-bay.test.mjs in a temporary directory. Run node --test --test-reporter=dot loading-bay.test.mjs there to print a dot per passing test.
import { rejects, strictEqual } from "node:assert/strict";
import test from "node:test";
/** @param {number} number */
async function loadingBay(number) {
if (number < 1) throw new RangeError("Bay numbers start at 1");
return `bay-${number}`;
}
test("formats a bay number", async () => {
strictEqual(await loadingBay(3), "bay-3");
});
test("rejects bay zero", async () => {
await rejects(loadingBay(0), RangeError);
});
Expected output#
..
The command exits with status 0. The default reporter includes details such as elapsed times, which vary between runs.
Common mistakes#
Await or return the promise from rejects() so the runner waits for the assertion to finish. A failed test makes node --test exit with status 1.
Version applicability#
node:test arrived in 16.17.0 in the 16.x line and in 18.0.0 in the 18.x line. The --test flag arrived in 16.17.0 and 18.1.0. The example’s dot reporter is available from 18.15.0 in the 18.x line and 19.6.0 in the 19.x line. The runner became stable in 20.0.0.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0