skip to content

Dependency-Free Testing

node --test runs describe/it suites with node:assert, mocks functions and timers, and reports coverage, with no dependency. Asked when it is enough and what a third-party framework still adds.

on this pageshow

explore

questions

6

In Node.js 24, which files does `node --test` run when given no file arguments, and how does it decide that each file passed?

level: juniorimportance: should knowfreq 30%

answer

  1. naming patterns, not a config file
  2. node_modules is never searched
  3. TypeScript extensions join the list
  4. one child process per file
  5. exit code 0 means the file passed

basics

~20 s

With no arguments, node --test runs every file outside node_modules named like *.test.js, _test.js or test-.js, or sitting in a test/ folder (plus .ts forms in Node 24), each in its own child process; a file passes when that process exits 0.

solid answer

~40 s

`node --test` with no file arguments searches the working directory, skipping `node_modules`, for names such as `**/*.test.{cjs,mjs,js}`, `**/*-test.*`, `**/*_test.*`, `**/test-*.*`, `**/test.*` and anything under a `test/` directory. In Node 24 the `.ts`, `.mts` and `.cts` forms match too, unless `--no-strip-types` is set. A `*.spec.js` file does not match, so you pass quoted globs such as `node --test "**/*.spec.js"`. By default each file runs in its own child process, and the file passes when that process exits with code 0, so a file does not even have to use `node:test`. Inside a file, a test fails when its function throws, its promise rejects or its callback gets a truthy error, and any failure sets exit code 1.

code

javascript · 13 lines
javascript
// src/math.test.mjs  (matches **/*.test.{cjs,mjs,js})
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

describe('sum', () => {
  it('adds two numbers', () => {
    assert.equal(1 + 2, 3);
  });

  it('fails when the promise rejects', async () => {
    await assert.rejects(Promise.reject(new Error('boom')), /boom/);
  });
});

go deeper

for a junior

Recall a few of the default name patterns, that node_modules is skipped, and that a file passes when its process exits 0. Know that *.spec.js needs an explicit glob.

for a middle

Explain the three ways a test function is judged, why a file without node:test still counts, and why an unawaited t.test() subtest gets cancelled.

for a senior

Point out how discovery surprises a real repository: helpers under test/ treated as test files, .ts files joining in Node 24, and the CI log switching to spec output.

for a principal

Treat the file-naming convention and the explicit glob in the test script as a team standard, so local runs, CI and editors all agree on what the suite contains.

## What `node --test` looks for `node --test` starts the **built-in test runner**, the command-line front end of the `node:test` module that ships inside the Node binary. Given no file arguments, it walks the current working directory, never descends into a `node_modules` directory, and collects every file whose name matches one of the default patterns: | Pattern | Example match | |---|---| | `**/*.test.{cjs,mjs,js}` | `src/user.test.js` | | `**/*-test.{cjs,mjs,js}` | `src/user-test.mjs` | | `**/*_test.{cjs,mjs,js}` | `src/user_test.cjs` | | `**/test-*.{cjs,mjs,js}` | `test-user.js` | | `**/test.{cjs,mjs,js}` | `lib/test.js` | | `**/test/**/*.{cjs,mjs,js}` | `test/helpers/db.js` | In Node 24 the same six shapes also match `.ts`, `.mts` and `.cts` files, because built-in type stripping is on by default; passing `--no-strip-types` removes those extra patterns. Two consequences catch teams out: - **`*.spec.js` is not a default pattern.** A suite named that way runs nothing until you pass a glob. - **Every JavaScript or TypeScript file under a `test/` directory counts as a test file**, including helper scripts. A helper that throws on import, or never exits, turns into a failing test file. To choose files yourself, put one or more glob patterns at the end of the command, in double quotes so the shell does not expand them first: `node --test "**/*.spec.js" "**/*.test.js"`. ## How each file is executed With the default **process-level isolation** (`--test-isolation=process`), every matched file runs in a **separate child process**, as if you had run it with `node` yourself. The runner keeps several of those processes going at once, up to `--test-concurrency`, which defaults to `os.availableParallelism() - 1`. The parent collects each child's results and prints them through one reporter. The verdict for a file is its child's **exit code**: 0 means passed, anything else means failed. That is why the documentation says a test file must be executable by Node.js but is not required to use `node:test` at all. A plain script that calls `process.exit(1)` on a bad result is a valid test file. Inside one file, the tests that `node:test` defines run on that process's single application thread. The `test()` option `concurrency` defaults to `false`, so a file's tests run **one at a time** in declaration order unless you opt in. ## What counts as pass or fail inside a file A test function created with `test()` or its alias `it()` (and grouped with `describe()`, an alias of `suite()`) is judged in one of three ways: 1. **Synchronous**: it fails if it throws, and passes otherwise. 2. **Promise-returning** (an `async` function, for example): it fails if the promise rejects, and passes if it fulfils. 3. **Callback**: if the function declares a second parameter, Node passes a `done` callback; calling it with a truthy first argument fails the test. A function that takes the callback **and** returns a promise fails. A few other rules shape the result: - If any test fails, the process **exit code is set to 1**, which is what fails the file. - A test marked `todo` still runs, but its failure does not count; a test marked `skip` never runs. - A subtest created with `t.test()` must be awaited. Once the parent finishes, any subtest still outstanding is **cancelled and treated as a failure**. ## Running a subset Three narrower ways to run tests are worth knowing, because they behave differently: - **Name the files**: `node --test src/user.test.js` runs only that file, still in a child process with the usual reporter. - **Filter by test name**: `--test-name-pattern="login"` runs only tests whose name matches the regular expression, and `--test-skip-pattern` does the opposite. Name patterns never change *which files* run; every matched file still starts. - **Run the file directly**: `node src/user.test.js` executes it as a normal script. Its `node:test` tests still run and report, but there is no discovery, no isolation between files and no parent process collecting results. ## Reading the result The default reporter is **`spec`**, a human-readable tree with a summary of tests, suites, passes, failures, cancellations, skips and todos. Since Node 23.0.0 it is the default on non-TTY output as well, so a CI log shows `spec` rather than the TAP format older releases printed there; `--test-reporter=tap` brings TAP back. The parent process's own exit code is non-zero when any file failed, which is the signal a CI step reads. `--test` cannot be combined with `--watch-path`, `--check`, `--eval`, `--interactive` or the inspector, so debugging one file usually means running it directly with `node` and the inspector instead.

  • Your team's files are all named `*.spec.js`, and `node --test` reports zero tests. Why, and what are the fixes?
    `*.spec.js` is not among the default patterns, so discovery finds nothing. Either pass the glob explicitly, quoted so Node expands it, as in `node --test "**/*.spec.js"`, and put that in the project's test script, or rename the files to `*.test.js`. Renaming keeps a bare `node --test` working for anyone who runs it.
  • Can `node --test` run a file that never imports `node:test`?
    Yes. Under the default process isolation each file is run as an ordinary script in a child process, and the runner judges it by its exit code alone: 0 passes, anything else fails. That lets an existing assertion script or a smoke check join the suite unchanged, though it reports as one test with no inner detail.
  • What happens to a subtest started with `t.test()` that the parent test does not await?
    The parent test does not wait for it. When the parent finishes, any subtest still running is cancelled and reported as a failure, which fails the parent too. Await every `t.test()` call, or use `describe()` and `it()`, where the suite waits for its tests on its own.

  • node --test picks up *.spec.js files by default
  • By default all test files share one process, so globals leak between files
  • A file must import node:test, or node --test refuses to run it
  • Tests inside one file run in parallel unless you turn concurrency off
  • A todo test that throws still fails the run

Assumes Node 24: .ts, .mts and .cts test files are discovered by default because type stripping is on, and spec has been the default reporter on non-TTY output since Node 23.0.0.

open as a page

In Node.js `node:test`, how do `mock.fn()` and `mock.method()` record calls, and when does the original behaviour come back?

level: middleimportance: should knowfreq 28%

basics

~20 s

Both return a Proxy whose .mock property records every call's arguments, result, error and this; mocks made through the test context's t.mock are restored when the test ends, while the top-level mock keeps its mocks until mock.reset() or mock.restoreAll().

open as a page

In Node.js `node:test`, how does `mock.timers` let a test of retry or timeout logic run without waiting, and what does it not intercept?

level: middleimportance: should knowfreq 25%

basics

~20 s

mock.timers.enable() replaces setTimeout, setInterval, setImmediate, Date and a few related APIs with fakes on one virtual clock, and tick(ms) or runAll() fires due callbacks synchronously; timers destructured from node:timers and other time sources escape it.

open as a page

In Node 24's built-in test runner, a suite passes with plain `node --test` but fails under `--test-isolation=none`. What explains it, and how do you find the culprit?

level: seniorimportance: should knowfreq 20%

basics

~20 s

By default each test file runs in its own child process, so module singletons, globals, process.env edits and top-level mocks die with the file; --test-isolation=none imports every file into one process, exposing tests that depend on shared state or order.

open as a page

Would you replace a Node 24 service's third-party test framework with the built-in `node:test` runner, and how would you decide and stage the switch?

level: principalimportance: should knowfreq 15%

basics

~20 s

Switch when the suite mostly needs what node:test ships stably, such as suites, hooks, node:assert, function and timer mocks, snapshots and reporters; keep the framework while the suite leans on module mocking or plugins, and migrate file by file.

open as a page

How do you make Node 24's built-in test runner fail a CI build when line coverage drops, and what can its coverage report miss?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Run node --test with --experimental-test-coverage and a threshold such as --test-coverage-lines=80, which exits with code 1 below the bar; the V8-based report omits files no test loads and, by default, test files, node_modules and core modules.

open as a page