The built-in test runner

Beginner · 7 min

Writing and running tests with node:test and node:assert: describe and it, hooks, node --test, watch mode, filtering, snapshots and coverage.

Before thisRunning code, the REPL and the CLIES modules in Node and interop

Snyk · 24 min · from 1:17

The built-in test runner

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by SnykReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `node:test` ships with Node. `import { describe, it, test } from 'node:test'` gives you a runner with suites, hooks, async support and reporters, with nothing to install.
  • `node --test` finds files named `*.test.js`, `*-test.js`, `*_test.js` or anything under a `test` directory, and runs each in its own process.
  • `node:assert/strict` is the assertion library. Use `assert.equal`, `assert.deepEqual` and `assert.throws`. The strict version compares with `===` semantics, so `1` and `'1'` differ.
  • Hooks are `before`, `after`, `beforeEach` and `afterEach`. Tests can be async, and a returned promise that rejects fails the test.
  • `--watch` reruns tests when files change, `--test-name-pattern` filters by name, and `--experimental-test-coverage` prints a line, branch and function coverage table. Coverage thresholds such as `--test-coverage-lines` fail the run when missed.
  • A test marked `{ todo: true }` is reported but does not fail the run, and `{ skip: true }` is not run. A todo test that fails still prints its error, which can look alarming.
  • Snapshots (`t.assert.snapshot`) and mocking (`mock.fn`) are built in too, so many projects need no separate test framework.

Why a runner ships with Node

A test framework does three jobs: find your test files, run them with isolation and reporting, and give you assertions to say what should be true. For years that meant installing Mocha, Jest or Jasmine before writing a line of test code. Node now includes all three, which is a good deal for a library or service that wants no extra dependencies and no config file.

That also makes it the baseline the next lessons compare against. Vitest and Jest add more, and it helps to know what you get without them. The wider question of what to test, and how, is in frontend testing strategies for UI code and testing backend services with real dependencies for services. This lesson is the tool.

A first test file

I ran all of this on Node 26. Because the tests use import, the project needs "type": "module" in package.json, as in ES modules in Node. Without it, Node tried to load the test file as CommonJS and failed with Cannot use import statement outside a module.

// cart.js
export function total(items) {
  return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
export function applyDiscount(amount, pct) {
  if (pct < 0 || pct > 100) throw new RangeError('pct must be 0-100');
  return amount * (1 - pct / 100);
}
// cart.test.js
import { describe, it, test } from 'node:test';
import assert from 'node:assert/strict';
import { total, applyDiscount } from './cart.js';

describe('total', () => {
  it('sums price times quantity', () => {
    assert.equal(total([{ price: 5, qty: 2 }, { price: 1, qty: 3 }]), 13);
  });
  it('is 0 for an empty cart', () => assert.equal(total([]), 0));
});

describe('applyDiscount', () => {
  it('rejects out-of-range input', () => {
    assert.throws(() => applyDiscount(100, 150), { name: 'RangeError', message: /0-100/ });
  });
});

test('async tests just return a promise', async () => {
  const price = await Promise.resolve(42);
  assert.equal(price, 42);
});

Run it:

node --test

Node discovers cart.test.js by name, runs it in a child process, and prints a tree of passing and failing tests with timings and a summary count. The default patterns are *.test.js, *-test.js, *_test.js, test.js, and files in any test directory (plus the .mjs and .cjs forms). A file called cart.spec.js is not found unless you pass a path or glob yourself.

describe and it are the Mocha-style names, and test is the same function as it, which is usable at the top level. Tests can be async, and a rejected promise fails the test.

Assertions

node:assert is built in too. Use the strict variant:

import assert from 'node:assert/strict';

assert.equal(1, 1);                          // ===
assert.deepEqual({ a: [1, 2] }, { a: [1, 2] }); // structural, strict
assert.throws(() => fn(), { name: 'RangeError' });
await assert.rejects(asyncFn(), /message/);

In the plain node:assert, equal uses ==, so assert.equal(1, '1') passes silently. The strict module avoids that. When an assertion fails, the error includes a diff of expected and actual, which is usually enough to see the problem.

Hooks, filtering and todos

Setup and teardown use before, after, beforeEach and afterEach, scoped to the enclosing describe. In a test of mine with one before, one beforeEach and two tests, the log came out before, each, each, which confirms the scoping.

Options go in an object as the second argument. { skip: true } doesn’t run a test, { todo: true } reports it as a todo, and { only: true } combines with --test-only. Be careful with todo bodies. A todo test that fails does not fail the run, but its assertion error is still printed, which can read like a real failure. For a placeholder, pass no function, as in test('not implemented yet', { todo: true }).

To run a subset, use a name pattern:

node --test --test-name-pattern="discount"

Watch mode and coverage

node --test --watch

re-runs affected tests when files change, which gives a fast feedback loop with no extra tools. Coverage is one flag:

node --test --experimental-test-coverage

It prints a table per file, with line, branch and function percentages and the uncovered line numbers. For my two functions all three columns read 100. The flag is still called --experimental-test-coverage in Node 26, even though it is widely used. Thresholds fail the run when missed, via --test-coverage-lines=80, --test-coverage-branches=70 and --test-coverage-functions=80. Coverage tells you which code never ran, not whether the assertions are good, so treat the number as a hint.

Snapshots and mocks

Two features people usually reach for Jest to get are available here. Snapshots use t.assert.snapshot(value) inside a test, with --test-update-snapshots to write or refresh the .snapshot file next to your test. I generated one and a second run passed against it. Mocking uses mock.fn() to create a function that records its calls, for example f.mock.callCount() and f.mock.calls[0].result. The next-but-one lesson, mocking and test doubles in Node, covers mocks in depth.

What the video covers

This lesson embeds a seven-minute section of Snyk’s “10 Node.js runtime features” video, from 1:17 to 8:42. Its chapters, in that range, are the Node.js test runner (1:17), native mocking (4:20), native test coverage (6:13) and watch mode (7:28). That matches this lesson closely. The rest of the video is about other features and is outside the clip. It is a vendor video, presented by Snyk’s Liran Tal, and it was recorded in May 2024 on Node 20, when coverage was still experimental. The flags above were rechecked against Node 26. The video’s transcript was not available, so this description is based on its chapter titles and description. Snapshots, thresholds, filtering and the discovery rules are carried by the prose. Daniel Bergholz’s eleven-minute “go deeper” video is a second introduction whose contents I could verify only from its title.

Where this fits

The built-in runner is enough for libraries, scripts and plenty of services. When you want a richer matcher API, module mocking with automatic hoisting, or browser-like environments, you reach for Vitest or Jest.

Check yourself

  1. 01You run `node --test` and it finds no tests, though you have `cart.spec.js`. Why?

    The default patterns do not include `.spec.js`. Node looks for files ending `.test`, `-test` or `_test` with a JavaScript extension, anything inside a `test` directory, and `test.js`. Rename the file, put it in `test/`, or pass the path or a glob explicitly, such as `node --test 'src/**/*.spec.js'`.

  2. 02Why use `node:assert/strict` rather than `node:assert`?

    The plain module's `equal` and `deepEqual` use loose `==` comparison, so `assert.equal(1, '1')` passes. The strict module makes `equal` mean `===` and `deepEqual` mean `deepStrictEqual`, which catches type mix-ups and prints better diffs.

  3. 03How do you find out which lines of your code the tests never run?

    Run `node --test --experimental-test-coverage`. It prints a table with line, branch and function percentages per file and the uncovered line numbers. Add `--test-coverage-lines=80` and similar flags to fail the run below a threshold.

  4. 04What is the difference between `describe`/`it` and `test` in `node:test`?

    Nothing important at runtime. `describe` creates a suite and `it` creates a test inside it, borrowing the names from Jasmine and Mocha. `test` is the same function as `it` and can be used at the top level or nested for subtests. Pick one style and stay consistent.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark