Explain it simply
The Node test runner in plain language
A test is a small piece of code that calls your code and checks that the result is what you expected. Node.js ships a test runner (node:test) and an assertion library (node:assert), so you can run tests with a single node --test command without installing Jest or Mocha.
It is like a cook tasting the dish every time something is added. Each time you change code you rerun the tests and know within seconds that what worked before still works.
Problem → Why → Solution
The problem: tests that flake or test nothing
One team's test suite talks directly to a real staging database and a payment sandbox. A run takes several minutes, fails randomly on days the network is slow, and developers have learned to fix a red build by simply rerunning it. Worst of all are tests with an un-awaited async assertion: they show green even though the bug is there.
import test from 'node:test';
import assert from 'node:assert';
test('rejects an empty cart', () => {
// Not awaited and not returned: the test finishes before the promise settles.
assert.rejects(checkout([]), /cart is empty/);
});
test('charges the card', async () => {
await checkout(cart, realPaymentSandbox); // slow, flaky, costs money
});Why these tests cannot be trusted
A test's result should depend only on the code, not on the network, the clock, or data left behind by another run. If a promise is not awaited, the runner marks the test as passed as soon as the function returns, and the failure that arrives later no longer belongs to that test.
Core concept: arrange, act, assert, at two levels
test(name, fn) registers one test. If fn throws or the promise it returns rejects, the test fails; if it finishes, it passes. describe and it group tests, and the hooks before, after, beforeEach and afterEach handle setup and cleanup. Tests inside one file run in order, and node --test runs each file in its own process.
Import assertions from node:assert/strict. In strict mode equal uses === and deepEqual also compares types, so "5" and 5 are not considered equal. Use assert.throws(fn, expected) for synchronous errors and await assert.rejects(promise, expected) for promises; the await is not optional.
Every test has three steps: arrange the state, act by calling one behaviour, and assert an observable result. Unit tests check pure functions in memory within milliseconds. Integration tests check a boundary: server.listen(0) asks the OS for a free port, fetch sends a real HTTP request, and the test checks the status and JSON body. Port 0 means two test files running at once never fight over a port.
Design slow, paid or external dependencies to be passed in as parameters. Then a test can pass a fake made with mock.fn() and check how many times and with which arguments it was called.
A good test gives the same answer on every run. Instead of reading Date.now() inside a function, pass in a clock such as now(), and inject random values from outside too. Never let one test depend on data another test left behind: each test must also pass when it runs on its own.
| Level | What it checks | Speed |
|---|---|---|
| Unit | one pure function, in memory only | milliseconds |
| Integration | one boundary, such as an HTTP route or a query | tens of ms per test |
| End-to-end | the whole deployed system | seconds |
- Arrange: inputs, fakes, server(0)
- Act: call exactly one behaviour
- Assert: check the result strictly
- Clean up with t.after or after()
A server or timer that is not cleaned up keeps the test process alive and can hang the whole suite.
General pattern
import { describe, it, before, after } from 'node:test';
import assert from 'node:assert/strict';
describe('unit under test', () => {
before(async () => { /* start shared resources, e.g. server.listen(0) */ });
after(async () => { /* close them */ });
it('does one thing', () => assert.equal(actual(), expected));
it('fails loudly', async () => await assert.rejects(promise(), /message/));
});describe groups tests, hooks open and close resources, each it checks one behaviour, and async assertions are awaited. From the command line you run node --test.
Worked example: unit tests plus an HTTP test
Normally pricing.mjs and pricing.test.mjs live in your project and you run node --test. To keep this example in one file, it writes both files to a temp folder and runs them programmatically with run() from node:test. run() returns a stream of test events, so the demo prints results itself without timing data that changes on every run. One test is deliberately wrong so you can see what a failure looks like.
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { run } from 'node:test';
// In a project these two files sit next to each other on disk and you run
// `node --test`. Here they are written to a temp folder so the demo is one file.
const dir = await mkdtemp(join(tmpdir(), 'node-test-demo-'));
await writeFile(join(dir, 'pricing.mjs'), `
export function applyDiscount(price, percent) {
if (percent < 0 || percent > 100) throw new RangeError('percent must be 0-100');
return Math.round(price * (100 - percent)) / 100;
}
`);
await writeFile(join(dir, 'pricing.test.mjs'), `
import test from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { applyDiscount } from './pricing.mjs';
test('applies a 20% discount', () => {
assert.equal(applyDiscount(50, 20), 40);
});
test('rejects an impossible percentage', () => {
assert.throws(() => applyDiscount(50, 120), RangeError);
});
test('GET /price returns the discounted price', async (t) => {
const server = createServer((req, res) => {
const base = Number(new URL(req.url, 'http://x').searchParams.get('base'));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ price: applyDiscount(base, 10) }));
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
t.after(() => server.close());
const url = 'http://127.0.0.1:' + server.address().port + '/price?base=30';
const response = await fetch(url);
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { price: 27 });
});
test('a deliberately wrong expectation', () => {
assert.equal(applyDiscount(10, 50), 4);
});
`);
let passed = 0;
let failed = 0;
for await (const { type, data } of run({ files: [join(dir, 'pricing.test.mjs')] })) {
if (data?.nesting !== 0) continue; // only top-level tests
if (type === 'test:pass') {
passed += 1;
console.log(`pass ${data.name}`);
} else if (type === 'test:fail') {
failed += 1;
const { expected, actual } = data.details.error.cause;
console.log(`FAIL ${data.name}: expected ${expected}, got ${actual}`);
}
}
console.log(`${passed} passed, ${failed} failed`);
await rm(dir, { recursive: true, force: true });Code breakdown
- Strict assertions
import assert from 'node:assert/strict';The strict variant makes equal use ===, so the legacy == mistake of treating "40" and 40 as equal cannot happen.
- Synchronous error
assert.throws(() => applyDiscount(50, 120), RangeError);The call is wrapped in an arrow function so assert.throws can invoke it and catch the error. The second argument also checks the error class.
- Real server on a free port
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));Port 0 lets the OS pick any free port; server.address().port tells you which one it chose.
- Cleanup that always runs
t.after(() => server.close());t.after runs even when an assertion fails. An open server would keep the child process alive and hang the suite.
- Read the event stream
for await (const { type, data } of run({ files: [join(dir, 'pricing.test.mjs')] })) {run() executes the file in a child process, as node --test does, and yields events such as test:pass and test:fail. A failure's details.error.cause carries expected and actual.
pass applies a 20% discount
pass rejects an impossible percentage
pass GET /price returns the discounted price
FAIL a deliberately wrong expectation: expected 4, got 5
3 passed, 1 failedFake dependencies and async assertions
checkout takes the card-charging function as a parameter, so the test can pass a fake created with mock.fn(). The fake records every call in mock.calls, and mock.callCount() reports how many there were. The second test checks a promise rejection with await assert.rejects. Run the file with node --test, or directly with node, and the results print in TAP or spec format.
// cart.test.mjs: run with `node --test`; tests in one file run in order.
import { describe, it, mock } from 'node:test';
import assert from 'node:assert/strict';
async function checkout(cart, chargeCard) {
if (cart.length === 0) throw new Error('cart is empty');
const total = cart.reduce((sum, item) => sum + item.price, 0);
await chargeCard(total);
return total;
}
describe('checkout', () => {
it('charges the card once with the total', async () => {
const chargeCard = mock.fn(async () => {}); // a fake payment gateway
const total = await checkout([{ price: 5 }, { price: 7 }], chargeCard);
assert.equal(total, 12);
assert.equal(chargeCard.mock.callCount(), 1);
assert.deepEqual(chargeCard.mock.calls[0].arguments, [12]);
});
it('rejects an empty cart', async () => {
await assert.rejects(checkout([], mock.fn()), /cart is empty/); // await it!
});
});| Command | What it does |
|---|---|
| node --test | finds files named like *.test.mjs and runs them |
| node --test --watch | reruns tests whenever a file changes |
| node --test --test-name-pattern="discount" | runs only tests whose name matches |
| node --test --experimental-test-coverage | prints a coverage report (experimental in Node 22) |
In real projects
How real projects organise tests
In an API project most tests are unit tests for validation, price calculation and permission rules. A few integration tests per route start the app with listen(0) and check status codes, headers and error bodies. These tests run in CI on every pull request, and a failure blocks the merge.
- Export the app from a factory such as createApp() and call listen only in the entry point, so each test can start its own instance.
- When the database must be tested, run each test inside a transaction that is rolled back, or use a separate test database in a container; never shared staging data.
- Pass email, payment and third-party API clients in through parameters or constructors, and replace them with fakes in tests.
Common mistakes
Common testing mistakes
Not awaiting assert.rejects
assert.rejects returns a promise. Without await or return, the test function finishes immediately and passes, and the later failure is no longer attached to that test. Make the test async and put await in front of every promise-returning assertion.
Fixed ports and servers that are never closed
listen(3000) fails with EADDRINUSE when another app is running on the developer's machine or when two test files run at once. A server that is never closed keeps the test process alive until the CI job times out. Use listen(0) and call close() in after or t.after.
Testing implementation details
A test that checks how often a private helper is called breaks on every refactor without catching bugs. Assert observable behaviour instead: return values, HTTP responses, or calls made to an external dependency.
Mini challenge
Mini challenge: test a config parser and a health endpoint
Test an app.mjs that exports parsePort and createApp. Write three unit tests for parsePort, then in a describe group start the server once on port 0 with a before hook and check /health and an unknown route. Run everything with run() and print the results indented by nesting level.
- parsePort: defaults to 3000, "8080" becomes 8080, text is rejected
- Start the server with listen(0) in before and close() it in after
- GET /health returns 200 with { ok: true }; an unknown route returns 404
- Print test:pass and test:fail events indented by data.nesting
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { run } from 'node:test';
const dir = await mkdtemp(join(tmpdir(), 'config-tests-'));
// TODO: write app.mjs exporting parsePort(raw = '3000') and createApp()
// (createApp answers /health with {"ok":true} and everything else with 404)
// TODO: write app.test.mjs:
// describe('parsePort') with three it() cases
// describe('HTTP app') with before/after hooks and two it() cases
// TODO: for await over run({ files: [...] }) and print
// ' '.repeat(data.nesting) + (pass ? 'ok ' : 'NOT') + ' ' + data.name
// TODO: remove dirExpected: All five tests show ok, and each suite (parsePort and HTTP app) shows ok without indentation after its child tests.
Show hint
Declare let server; let base; inside the describe and assign them in before. Return new Promise((resolve) => server.close(resolve)) from after so the runner waits until the server is closed.
Show solution
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { run } from 'node:test';
const dir = await mkdtemp(join(tmpdir(), 'config-tests-'));
await writeFile(join(dir, 'app.mjs'), `
import { createServer } from 'node:http';
export function parsePort(raw = '3000') {
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Invalid PORT: ' + raw);
}
return port;
}
export function createApp() {
return createServer((req, res) => {
if (req.url === '/health') return res.end(JSON.stringify({ ok: true }));
res.statusCode = 404;
res.end();
});
}
`);
await writeFile(join(dir, 'app.test.mjs'), `
import { after, before, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { createApp, parsePort } from './app.mjs';
describe('parsePort', () => {
it('defaults to 3000', () => assert.equal(parsePort(undefined), 3000));
it('parses a numeric string', () => assert.equal(parsePort('8080'), 8080));
it('rejects text', () => assert.throws(() => parsePort('http'), /Invalid PORT/));
});
describe('HTTP app', () => {
let server;
let base;
before(async () => {
server = createApp();
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = 'http://127.0.0.1:' + server.address().port;
});
after(() => new Promise((resolve) => server.close(resolve)));
it('GET /health answers ok', async () => {
const res = await fetch(base + '/health');
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), { ok: true });
});
it('unknown routes return 404', async () => {
const res = await fetch(base + '/nope');
assert.equal(res.status, 404);
});
});
`);
const results = [];
for await (const { type, data } of run({ files: [join(dir, 'app.test.mjs')] })) {
if (type === 'test:pass' || type === 'test:fail') {
const mark = type === 'test:pass' ? 'ok ' : 'NOT';
results.push(`${' '.repeat(data.nesting)}${mark} ${data.name}`);
}
}
console.log(results.join('\n'));
await rm(dir, { recursive: true, force: true });Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- node:test and node:assert/strict ship with Node.js and run with node --test.
- Always await assertions that return promises, such as assert.rejects.
- Integration tests call a real server on listen(0) with fetch and close it in an after hook.
- Pass external dependencies in as parameters and replace them with mock.fn() in tests.
Test runner — Node.js