Lesson 30 / 30
Testing with node:test
Write and run unit tests with Node's built-in test runner and the assert module, with no extra dependencies.
The built-in test runner
Since Node 20 the test runner is stable. Import test from node:test and use node:assert for checks.
// add.test.js
import test from "node:test";
import assert from "node:assert/strict";
import { add } from "./math.js";
test("adds two numbers", () => {
assert.equal(add(2, 3), 5);
});
test("async works", async () => {
const data = await Promise.resolve(42);
assert.equal(data, 42);
});Run all test files, watch for changes and collect coverage.
node --test
node --test --watch
node --test --experimental-test-coverageKeep tests small and independent, name them after the behaviour, and run them in CI on every push.
Quick check
Quick check: Which command runs Node's built-in tests?
- node --test
- npm install test
- node --check
- node --lint
Answer
node --test — `node --test` discovers and runs test files with the built-in runner.