Testing with node:test
Automated tests are small programs that check your real program. They catch bugs before your users do and let you refactor without fear. Node used to need third-party tools (Mocha, Jest, AVA…), but since Node 18 it has a built-in test runner, node:test, plus the node:assert module for checks. Both are stable and need no installation.
Assertions with node:assert
An assertion is a statement that must be true. If it isn't, it throws an AssertionError. Use the strict variant, which compares with === semantics:
const assert = require('node:assert/strict');
function slugify(title) {
return title.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}
assert.equal(slugify('Hello World'), 'hello-world');
assert.equal(slugify(' Node.js 22 is out! '), 'node-js-22-is-out');
assert.deepEqual([1, 2].map((n) => n * 2), [2, 4]);
assert.ok(slugify('x').length > 0);
console.log('all assertions passed');
try {
assert.equal(slugify('C++ Rocks'), 'c++-rocks');
} catch (err) {
console.log(err.name, '-', err.code);
console.log('actual:', err.actual, '| expected:', err.expected);
}all assertions passed
AssertionError - ERR_ASSERTION
actual: c-rocks | expected: c++-rocks
| Assertion | Passes when |
|---|---|
assert.equal(a, b) |
a === b (strict mode) |
assert.notEqual(a, b) |
a !== b |
assert.deepEqual(a, b) |
objects/arrays have equal content |
assert.ok(value) |
value is truthy |
assert.throws(fn, expected) |
fn() throws a matching error |
assert.rejects(promise, expected) |
the promise rejects (use with await) |
assert.match(str, /re/) |
the string matches the regex |
Writing tests with test()
The test runner groups assertions into named tests. A test passes if its function returns (or its promise resolves) without throwing. Put tests in files named like *.test.js:
// math.test.js
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { add, divide } from './math.js';
describe('add', () => {
test('adds two numbers', () => {
assert.equal(add(2, 3), 5);
});
test('works with negatives', () => {
assert.equal(add(-2, -3), -5);
});
});
describe('divide', () => {
test('divides', () => {
assert.equal(divide(10, 4), 2.5);
});
test('refuses to divide by zero', () => {
assert.throws(() => divide(1, 0), { message: 'Division by zero' });
});
test('async code works too', async () => {
const result = await Promise.resolve(divide(9, 3));
assert.equal(result, 3);
});
});it is an alias for test, so code written for Mocha or Jest often needs very few changes.
Running the tests
node --test finds test files automatically (*.test.js, *-test.js, *_test.js, files in a test folder, and the .mjs/.cjs variants) and runs each in its own process. The real output includes the duration of every test, which changes from run to run, so the session below is simulated with fixed timings:
$ node --test
▶ add
✔ adds two numbers (0.512ms)
✔ works with negatives (0.087ms)
✔ add (1.201ms)
▶ divide
✔ divides (0.095ms)
✔ refuses to divide by zero (0.211ms)
✔ async code works too (0.130ms)
✔ divide (0.702ms)
ℹ tests 5
ℹ suites 2
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 48.3▶ add
✔ adds two numbers (0.512ms)
✔ works with negatives (0.087ms)
✔ add (1.201ms)
▶ divide
✔ divides (0.095ms)
✔ refuses to divide by zero (0.211ms)
✔ async code works too (0.130ms)
✔ divide (0.702ms)
ℹ tests 5
ℹ suites 2
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 48.3
When a test fails, the runner prints the assertion's actual and expected values and the process exits with code 1 — which is exactly what CI systems such as GitHub Actions look for.
Useful flags and options:
| Command / option | Effect |
|---|---|
node --test --watch |
re-run tests when files change |
node --test --test-name-pattern="divide" |
only run tests whose name matches |
node --test --experimental-test-coverage |
print a code-coverage report |
node --test --test-reporter=dot |
compact output (spec, tap, junit also exist) |
test.skip('…', fn) / test.todo('…') |
mark a test as skipped / not written yet |
test.only('…', fn) + --test-only |
run just this test while debugging |
Add a script to package.json so everyone runs tests the same way: "test": "node --test", then npm test.
Hooks and mocks
Setup and cleanup code goes into hooks: before, after, beforeEach and afterEach. For replacing functions, node:test includes mock:
import { test, beforeEach, mock } from 'node:test';
import assert from 'node:assert/strict';
let cart;
beforeEach(() => { cart = []; }); // fresh state for every test
test('mock.fn records calls', () => {
const sendEmail = mock.fn(() => 'sent');
checkout(cart, sendEmail);
assert.equal(sendEmail.mock.callCount(), 1);
assert.deepEqual(sendEmail.mock.calls[0].arguments, ['Your order is confirmed']);
});Running tests inside one script
You don't strictly need --test: running a file that calls test() with plain node also executes the tests. The playground below is a tiny hand-made "runner" with no timings, so you can experiment with passing and failing checks right here:
const assert = require('node:assert/strict');
const results = [];
function check(name, fn) {
try {
fn();
results.push(`ok ${name}`);
} catch (err) {
results.push(`FAIL ${name}: ${err.message.split('\n')[0]}`);
}
}
const isLeapYear = (y) => (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
check('2024 is a leap year', () => assert.equal(isLeapYear(2024), true));
check('1900 is not a leap year', () => assert.equal(isLeapYear(1900), false));
check('2000 is a leap year', () => assert.equal(isLeapYear(2000), true));
check('throws on bad JSON', () => assert.throws(() => JSON.parse('{oops}'), SyntaxError));
check('deliberately wrong', () => assert.equal(isLeapYear(2023), true));
console.log(results.join('\n'));
console.log(`${results.filter((r) => r.startsWith('ok')).length}/${results.length} passed`);ok 2024 is a leap year
ok 1900 is not a leap year
ok 2000 is a leap year
ok throws on bad JSON
FAIL deliberately wrong: Expected values to be strictly equal:
4/5 passed
Tip: Test behaviour, not implementation: check what a function returns for given inputs, so you can rewrite how it works without touching the tests.
Test yourself
Which import gives you assertions that compare with strict equality?
node:assert/strictnode:test/assertnode:checkassert-strictfrom npm
What command runs all *.test.js files with the built-in runner?
npm run jestnode testnode --testnode --run-tests
How does the test runner signal failing tests to a CI system?
- It deletes the test file
- It exits with a non-zero exit code
- It prints in red only
- It sends an email