Node ships a test runner. If your project is a service, a CLI, or a library that already runs on a current LTS, you can delete the test framework from package.json and run node --test instead — no transform step, no config file, no separate assertion library, and one fewer dependency tree to audit. The trade is that a few of the pieces you will want in CI, coverage in particular, are still marked experimental, and a couple of the flags below simply do not exist on older Node. This guide builds a working suite on Node 22 LTS, states the version each feature needs, and ends with a CI job that publishes JUnit results.
What you’ll accomplish
- Run a suite with
node --test, understanding exactly which files it picks up and why. - Write tests with
test,describe,it, subtests, and lifecycle hooks fromnode:test, asserting withnode:assert/strict. - Replace a method and freeze the clock with
t.mock, and understand what gets restored for you. - Produce a coverage table and a
junit.xmlfile from the same run, with a non-zero exit code on failure. - Wire the whole thing into a GitHub Actions job that uploads the results as an artifact.
Prerequisites
- Node 22 LTS is what this guide targets. Everything here works on 22.11 or newer; several flags do not exist earlier.
node:testand thenode --testflag are usable from Node 18, but the module was only marked stable in Node 20.0.0.describeanditarrived in 18.6.0.- The
junitreporter needs Node 21.0.0 or newer, so on Node 20 you gettap,spec, anddotonly. Thelcovreporter needs Node 22. --test-concurrencyneeds Node 21.0.0.--test-force-exitandt.plan()need Node 22 (22.0.0 and 22.2.0 respectively).- Coverage is still gated behind
--experimental-test-coverageon Node 20 and 22. Threshold flags such as--test-coverage-lineslanded in 22.8.0. - Mock timers (
t.mock.timers) arrived in 20.4.0 and remain experimental; theenable({ apis })object form used below needs 20.11.0 or 21.2.0.
If you are stuck on Node 18 or 20 for other reasons, installing Node with nvm is the least disruptive way to get a 22 runtime beside the one you already have.
How it works
node --test runs as a small supervisor. It walks the working directory, selects files by name, and spawns one child process per test file. Each child gets its own V8 isolate and its own module registry, so a global that one file stomps on cannot reach another, and a file that segfaults takes down only itself. The children emit structured events back to the root process, which is where reporting, coverage merging, and the final exit code happen.
Discovery is purely by name, and this is where most first attempts go wrong. With no path arguments, the runner matches these patterns and skips node_modules entirely:
**/*.test.?(c|m)js
**/*-test.?(c|m)js
**/*_test.?(c|m)js
**/test-*.?(c|m)js
**/test.?(c|m)js
**/test/**/*.?(c|m)js
A file called cartSpec.js will never run. Either rename it or pass paths explicitly. Node 22 also accepts glob patterns as positional arguments, so node --test "src/**/*.spec.js" works there but not on Node 20.
Inside a file, execution order is boringly predictable, which matters far more than it sounds when you are debugging a leaky fixture.
Step-by-step
1. Confirm the runtime you actually have. Every version caveat above hangs off this number.
node --version
v22.14.0
2. Set the module system explicitly. The runner does not care whether you use ESM or CommonJS, but it will not guess. Declaring type once saves an afternoon of import errors.
npm pkg set type=module scripts.test="node --test"
node -p "require('./package.json').type"
module
3. Write the code under test. A small pure module keeps the example honest.
// src/cart.js
export function subtotal(items) {
return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
export function applyDiscount(amount, percent) {
if (percent < 0 || percent > 100) throw new RangeError('percent out of range');
return Math.round(amount * (1 - percent / 100));
}
4. Write the first test file. Use node:assert/strict so equal means === and you never debug a coercion you did not ask for.
// test/cart.test.js
import test from 'node:test';
import assert from 'node:assert/strict';
import { subtotal, applyDiscount } from '../src/cart.js';
test('sums line items', () => {
assert.equal(subtotal([{ price: 500, qty: 2 }, { price: 250, qty: 1 }]), 1250);
});
test('applies a percentage discount', () => {
assert.equal(applyDiscount(1000, 10), 900);
});
test('rejects an impossible discount', () => {
assert.throws(() => applyDiscount(1000, 140), RangeError);
});
5. Run it. No arguments, no config.
node --test
✔ sums line items (1.204125ms)
✔ applies a percentage discount (0.28925ms)
✔ rejects an impossible discount (0.41175ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 96.732
That is the spec reporter, chosen because stdout is a terminal. Pipe the same command into a file and you get TAP instead — which is why CI logs look nothing like your shell until you set a reporter explicitly.
6. Group with describe and it, and add hooks. describe and it are the same machinery with familiar names. Hooks come from the same module, not from a global.
// test/checkout.test.js
import { describe, it, before, beforeEach, after } from 'node:test';
import assert from 'node:assert/strict';
describe('checkout', () => {
let store;
before(() => {
// runs once for the whole suite
store = new Map();
});
beforeEach(() => {
store.clear();
store.set('sku-1', { price: 500, qty: 1 });
});
after(() => store.clear());
it('holds one line item', () => {
assert.equal(store.size, 1);
});
it('does not leak state between tests', () => {
store.set('sku-2', { price: 100, qty: 3 });
assert.equal(store.size, 2);
});
});
node --test test/checkout.test.js
▶ checkout
✔ holds one line item (0.9822ms)
✔ does not leak state between tests (0.3401ms)
▶ checkout (2.884ms)
ℹ tests 2
ℹ suites 1
ℹ pass 2
ℹ fail 0
7. Use subtests for table-driven cases, and await them. t.test() creates a child of the current test. If you do not await it, the parent finishes first and the runner cancels the subtest — it does not silently pass, but it also does not run your assertions.
// test/discount.test.js
import test from 'node:test';
import assert from 'node:assert/strict';
import { applyDiscount } from '../src/cart.js';
test('discount table', async (t) => {
const cases = [[1000, 0, 1000], [1000, 50, 500], [999, 10, 899]];
for (const [amount, percent, expected] of cases) {
await t.test(`${amount} at ${percent}%`, () => {
assert.equal(applyDiscount(amount, percent), expected);
});
}
});
8. Mock a method and the clock. t.mock is scoped to the test context, and everything it replaces is restored when that test ends. t.mock.timers is still experimental, so pin the APIs you want rather than freezing everything.
// test/retry.test.js
import test from 'node:test';
import assert from 'node:assert/strict';
const mailer = {
send() { throw new Error('smtp unavailable'); }
};
test('reports a delivery failure', (t) => {
t.mock.method(mailer, 'send', () => 'queued');
assert.equal(mailer.send(), 'queued');
assert.equal(mailer.send.mock.callCount(), 1);
});
test('backs off before retrying', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const fn = t.mock.fn();
setTimeout(fn, 60_000);
t.mock.timers.tick(60_000);
assert.equal(fn.mock.callCount(), 1);
});
node --test test/retry.test.js
✔ reports a delivery failure (1.061ms)
✔ backs off before retrying (0.7788ms)
ℹ pass 2
ℹ fail 0
9. Turn on watch mode while you work. The runner re-runs only what the changed file affects.
node --test --watch
✔ sums line items (0.98ms)
ℹ pass 3
Completed running 'test/cart.test.js'. Waiting for file changes before restarting...
10. Filter down when the suite grows. --test-name-pattern takes a regular expression matched against test names; --test-only runs only tests declared with { only: true }.
node --test --test-name-pattern="discount"
ℹ tests 4
ℹ pass 4
ℹ skipped 3
11. Add coverage. On Node 20 and 22 this is experimental and prints a warning; the numbers themselves are V8 counts and are trustworthy.
node --test --experimental-test-coverage
ℹ start of coverage report
ℹ ---------------------------------------------------------------
ℹ file | line % | branch % | funcs % | uncovered lines
ℹ ---------------------------------------------------------------
ℹ src/cart.js | 95.65 | 88.89 | 100.00 | 12
ℹ ---------------------------------------------------------------
ℹ all files | 95.65 | 88.89 | 100.00 |
ℹ ---------------------------------------------------------------
ℹ end of coverage report
12. Emit machine-readable results. Reporters pair with destinations positionally, so you can keep readable output on stdout while writing JUnit XML to a file. Both flags must be repeated together.
mkdir -p reports
node --test \
--experimental-test-coverage \
--test-reporter=spec --test-reporter-destination=stdout \
--test-reporter=junit --test-reporter-destination=reports/junit.xml
ℹ tests 8
ℹ pass 8
ℹ fail 0
13. Set concurrency deliberately. By default the root process runs several files at once (roughly one per CPU core, minus one). Cap it when your tests share a database, or raise per-file parallelism when they do not.
node --test --test-concurrency=2
Inside a file, subtests run one at a time unless you opt in:
describe('independent probes', { concurrency: true }, () => { /* ... */ });
Validate it works
Prove the failure path first, because a suite that cannot fail is decoration. Break one expectation on purpose:
node --test test/cart.test.js; echo "exit=$?"
✖ applies a percentage discount (1.318ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
900 !== 920
at TestContext.<anonymous> (file:///srv/app/test/cart.test.js:12:10)
ℹ tests 3
ℹ pass 2
ℹ fail 1
exit=1
Then confirm the CI artifacts exist and are well formed:
head -3 reports/junit.xml && wc -l reports/junit.xml
<?xml version="1.0" encoding="utf-8"?>
<testsuites>
<testsuite name="test/cart.test.js" tests="3" failures="0" errors="0" time="0.0964">
41 reports/junit.xml
Finally, the CI step itself. This is a complete workflow file; the if: always() matters, because without it a failing suite means no results to look at.
# .github/workflows/test.yml
name: test
on: [push, pull_request]
jobs:
node-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
- run: npm ci
- run: mkdir -p reports
- run: >
node --test
--experimental-test-coverage
--test-reporter=spec --test-reporter-destination=stdout
--test-reporter=junit --test-reporter-destination=reports/junit.xml
- uses: actions/upload-artifact@v4
if: always()
with:
name: junit-results
path: reports/junit.xml
Any CI system works the same way — the runner’s exit code is the only contract. If GitHub Actions itself is new to you, our GitHub Actions essentials covers caching, matrices, and required checks.
Troubleshooting
node --test reports zero tests. Discovery is by filename, full stop. cart.spec.js and tests/cart.js (plural directory) both miss every pattern. Rename to cart.test.js, move the directory to test/, or pass paths explicitly. Run node --test --test-reporter=tap to see the file list the runner actually built.
SyntaxError: Cannot use import statement outside a module. The file is being parsed as CommonJS. Either set "type": "module" in package.json or rename the file to .mjs. The mirror image — ReferenceError: require is not defined — means the opposite: you are in ESM and should use import, or rename that file to .cjs.
A test passes but the assertion never ran. Almost always an async test whose promise is not awaited: a callback-style API, or a t.test() subtest called without await. Subtests that have not settled when the parent finishes are cancelled, and unawaited work simply does not count. On Node 22, t.plan(2) inside the test makes this loud — the test fails if the expected number of assertions did not run.
Mocks leak into the next test. t.mock.* on the test context is restored automatically. The mock object imported directly from node:test is process-global and is not, so a mock.method() at module scope stays replaced for the rest of the file. Either switch to the context form or call mock.restoreAll() in an afterEach.
bad option: --experimental-test-coverage or --test-reporter=junit. The installed Node is too old for that flag. Coverage needs 18.15.0 or 20.1.0, and the junit reporter needs 21.0.0. Check node --version inside the CI container, not on your laptop; a setup-node step that pins node-version: '20' is a common cause of a green local run and a red pipeline.
Tests hang after the last assertion passes. An open handle — a timer, a socket, a database pool — is keeping the child process alive. Close it in an after() hook. --test-force-exit (Node 22) will end the process anyway, but treat that as a diagnostic rather than a fix.
When this is the wrong approach
Anything that needs a DOM is out of scope. There is no jsdom equivalent in node:test, no browser environment, and no component renderer; a React or Vue component suite belongs on Vitest or a browser-driven runner, and the built-in runner is a poor fit for that work.
Snapshot-heavy workflows are a genuine gap. Node has t.assert.snapshot(), but it is experimental, file-based, and nowhere near the inline-snapshot and interactive-update experience of a mature framework. If your team’s habit is to write a component test by recording output and eyeballing the diff, you will feel the loss immediately.
A large existing Jest suite is rarely worth migrating on principle. The runners disagree about globals, module mocking, jest.mock hoisting, and transforms, so a real migration is a rewrite of the mocking layer, not a find-and-replace. The honest case for switching is a new service, a library with no build step, or a suite small enough to port in a day.
And if you are testing compiled TypeScript, check where you stand: Node 22.6 added --experimental-strip-types, and later 22.x releases run annotated .ts files without a flag, but anything using enums or decorators still needs a build step ahead of the runner.
The authoritative references are the Node.js test runner documentation and the CLI options page, which is where you confirm the minimum version for every flag above against your own runtime.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.