← Back to Node.js, page 3

nodejs-0057 · Easy fresher

How do you write and run tests with the built-in node:test module?

node:test is a test runner built into Node. Write tests with test() or describe() and it(), check results with node:assert, and run them with node --test. It supports hooks, skipping, subtests, mocking, coverage and several reporters, so small projects need no extra dependency.

Full answer

Since Node 20 the built-in runner is stable. A test file looks like this:

const test = require('node:test'); const assert = require('node:assert/strict'); test('adds numbers', () => { assert.equal(1 + 2, 3); });

Run node --test. It finds files named *.test.js, *.spec.js, files in a test folder, and runs each file in its own process, in parallel.

Features:

  • describe and it (also suite): grouping, same idea as Jest and Mocha.
  • Hooks: before, after, beforeEach, afterEach.
  • test options: { skip: true }, { todo: true }, { only: true } with --test-only, { timeout: 1000 }, { concurrency: n }.
  • Async tests: return a promise or use an async function. A rejected promise fails the test.
  • Subtests: t.test(...) inside a test, and the context t gives t.mock, t.skip and t.diagnostic.
  • Reporters: spec (the default in a terminal), tap, dot, junit, lcov. Choose with --test-reporter.
  • Coverage: node --test --experimental-test-coverage (check the current flag name in the docs for your version).
  • Watch mode: node --test --watch.
  • Name filters: --test-name-pattern.

Exit code: 0 if all tests pass, 1 if any fail, which is what CI needs.

When to pick something else: if you need snapshot testing, a large plugin ecosystem or DOM tests, Jest or Vitest may fit better. For a backend library or service, node:test is often enough.

javascript
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'node-test-'));
fs.writeFileSync(path.join(dir, 'grades.js'), `
exports.grade = (marks) => (marks >= 75 ? 'A' : marks >= 40 ? 'B' : 'F');
`);
fs.writeFileSync(path.join(dir, 'grades.test.js'), `
const { describe, it, beforeEach, test } = require('node:test');
const assert = require('node:assert/strict');
const { grade } = require('./grades.js');

describe('grade()', () => {
  let calls;
  beforeEach(() => { calls = 0; });

  it('gives A for 75 and above', () => { calls++; assert.equal(grade(75), 'A'); });
  it('gives B for passing marks', () => assert.equal(grade(40), 'B'));
  it('gives F below 40', async () => assert.equal(grade(39), 'F'));
  it('is skipped on purpose', { skip: 'not ready' }, () => {});
});

test('this test fails (error on purpose)', () => assert.equal(grade(90), 'B'));
`);

const run = spawnSync(process.execPath, ['--test', '--test-reporter=tap'], { encoding: 'utf8', cwd: dir });

const lines = run.stdout.split('\n');
console.log(lines.filter((l) => /^\s*(ok|not ok) \d+ - /.test(l)).map((l) => l.replace(/ # SKIP.*/, ' (skipped)')).join('\n'));
for (const key of ['tests', 'pass', 'fail', 'skipped']) {
  console.log(key.padEnd(8), lines.find((l) => l.startsWith('# ' + key + ' ')).split(' ').pop());
}
console.log('exit code:', run.status);

fs.rmSync(dir, { recursive: true });

The run uses the tap reporter so that the output is easy to read in a script. One test fails on purpose, to show the exit code. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): ok 1 - gives A for 75 and above ok 2 - gives B for passing marks ok 3 - gives F below 40 ok 4 - is skipped on purpose (skipped) ok 1 - grade() not ok 2 - this test fails (error on purpose) tests 5 pass 3 fail 1 skipped 1 exit code: 1

Key points

  • node --test finds and runs test files.
  • test, describe, it and hooks work like other runners.
  • Pair it with node:assert.
  • Exit code 1 on failure, so CI works with no setup.

Common mistakes

  • Forgetting to name files so the runner finds them.
  • Using the old assert module (loose equality) instead of node:assert/strict.
  • Sharing state between tests without resetting it in beforeEach.
  • Not awaiting async work, so a test passes before the work ends.

Follow-ups

  • How does node:test run files in parallel and does it affect shared databases?
  • How do you run a single test by name?
  • How do you produce a JUnit report for CI?

Tips

  • Mention that it is built in and stable, which removes dependencies.
  • Use assert/strict by default.
  • Show that the exit code is how CI knows a test failed.