Node.js

Production JavaScript, Part 3: Testing With node:test, the Runner That's Already Installed

Node 26 ships a test runner with mocks, fake timers, snapshots and coverage, and it runs TypeScript tests with no build step. I wrote a real suite with it, broke it in the two most common ways, and timed the same 500 tests under node:test, Vitest 5 and Jest 30: 786 ms, 1,645 ms and 1,240 ms.

scientist using pipette with test tubes in lab
Photo by Julia Koblitz / Unsplash

Ask a JavaScript developer how to start testing a project and you'll get an answer that begins with npm install. Jest, Vitest, Mocha plus Chai plus Sinon: each brings a config file, a few hundred transitive dependencies and opinions about ESM. For a library, a CLI or a backend service, most of that is now optional, because Node has had a stable built-in test runner since version 20, and by Node 26 it covers what most backend code needs.

This is part 3 of the production JavaScript series. Part 1 was shutdown and part 2 was error handling. This one is about proving your code works before production does it for you. The suite below tests two real helpers, one of them the retry function every service ends up writing. I'll show the runner's features on real code with real output, the two mistakes that cost me a broken test run, and how it compares with Vitest and Jest on speed.

The Node.js Test Runner in One Command

The code under test is two small TypeScript modules. Node 26 runs .ts files directly through type stripping, so there's no build step for the code or the tests:

// Split an amount in integer cents by ratios; leftover cents go to the first shares.
export function allocate(totalCents: number, ratios: number[]): number[] {
  if (!Number.isSafeInteger(totalCents) || totalCents < 0) throw new RangeError("totalCents must be a non-negative safe integer");
  if (ratios.length === 0 || ratios.some((r) => r < 0)) throw new RangeError("ratios must be non-negative and non-empty");
  const sum = ratios.reduce((a, b) => a + b, 0);
  if (sum === 0) throw new RangeError("ratios must not all be zero");
  const shares = ratios.map((r) => Math.floor((totalCents * r) / sum));
  let left = totalCents - shares.reduce((a, b) => a + b, 0);
  for (let i = 0; left > 0; i = (i + 1) % shares.length, left--) shares[i]++;
  return shares;
}
// Retry an async operation with exponential backoff: 100 ms, 200 ms, 400 ms...
export async function retry<T>(fn: () => Promise<T>, attempts = 3, baseMs = 100): Promise<T> {
  let lastError: unknown;
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (err) {
      lastError = err;
      if (i < attempts - 1) await new Promise((r) => setTimeout(r, baseMs * 2 ** i));
    }
  }
  throw new Error(`failed after ${attempts} attempts`, { cause: lastError });
}

The tests use node:test for structure and node:assert/strict for checks:

import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { allocate } from "../src/money.ts";

describe("allocate", () => {
  it("splits $100 three ways without losing a cent", () => {
    assert.deepEqual(allocate(10000, [1, 1, 1]), [3334, 3333, 3333]);
  });
  it("always sums back to the total", () => {
    for (let total = 0; total < 2000; total += 7) {
      const parts = allocate(total, [3, 5, 11]);
      assert.equal(parts.reduce((a, b) => a + b, 0), total);
    }
  });
  it("rejects fractional cents", () => {
    assert.throws(() => allocate(10.5, [1, 1]), RangeError);
  });
  it("matches the snapshot for a 70/20/10 split", (t) => {
    t.assert.snapshot(allocate(500, [70, 20, 10]));
  });
});

Running everything takes one command and no config file:

▶ allocate
  ✔ splits $100 three ways without losing a cent (1.760393ms)
  ✔ always sums back to the total (1.037807ms)
  ✔ rejects fractional cents (0.710588ms)
  ✔ matches the snapshot for a 70/20/10 split (2.381797ms)
✔ allocate (8.581352ms)
✔ retries with backoff and succeeds on the third try, without waiting in real time (6.140806ms)
✔ keeps the last error as the cause (2.730928ms)
ℹ tests 6
ℹ suites 1
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 272.425947

Six tests in 272 ms total. What's built in:

Feature API Status in Node 26 docs
test, describe/it, hooks node:test Stable
Assertions node:assert/strict Stable
Function mocks and spies t.mock.fn(), t.mock.method() Stable (part of the module)
Fake timers t.mock.timers Stable (part of the module)
Snapshots t.assert.snapshot() "no longer experimental" since v23.4.0
Coverage --experimental-test-coverage Stability: 1 - Experimental
Watch mode node --test --watch Built in

Snapshots

The fourth money test uses t.assert.snapshot(). The first run with --test-update-snapshots writes a file next to the test, and you commit it:

exports[`allocate > matches the snapshot for a 70/20/10 split 1`] = `
[
  350,
  100,
  50
]
`;

Every run after that compares against the file and fails on any difference. Snapshots are good for outputs that are big, structured and easy to review by eye. They're bad as a replacement for thinking about what the right answer is, because a snapshot of a wrong result passes forever. For allocate(), the property test above it ("always sums back to the total," checked for 286 different totals) is the one that protects you. The snapshot only catches changes.

We recommend reading What is Node.JS? Using JavaScript without the Browser to continue reading our selection of content. If you're new to running JavaScript outside the browser, this explains what Node actually is before you test with it.

What is Node.JS? Using JavaScript without the Browser Node.js took the V8 engine out of Chrome and ran it on a server. That sounds like a small change. SudoSecurity · Santhdium

Fake Timers, and the Two Mistakes I Made First

Retry logic is the classic hard-to-test code: it sleeps, and nobody wants a test suite that waits 700 ms per case. Fake timers let a test move the clock instead of waiting. My first attempt used the module-level mock object:

import { it, mock } from "node:test";
import assert from "node:assert/strict";
import { retry } from "../src/retry.ts";

it("retries with backoff and succeeds on the third try, without waiting in real time", async () => {
  mock.timers.enable({ apis: ["setTimeout"] });
  const fn = mock.fn(async () => {
    if (fn.mock.callCount() < 3) throw new Error("flaky");   // callCount includes the current call
    return "ok";
  });
  const p = retry(fn, 3, 100);
  for (let i = 0; i < 2; i++) {               // let each failure settle, then jump the clock past its backoff
    await new Promise(setImmediate);
    mock.timers.tick(100 * 2 ** i);
  }
  assert.equal(await p, "ok");
  assert.equal(fn.mock.callCount(), 3);
  mock.timers.reset();
});

it("keeps the last error as the cause", async () => {
  const err = await retry(async () => { throw new Error("db down"); }, 2, 1).catch((e) => e);
  assert.match(err.message, /failed after 2 attempts/);
  assert.equal(err.cause.message, "db down");
});
✖ retries with backoff and succeeds on the third try, without waiting in real time (3.171061ms)
✖ keeps the last error as the cause (5002.369341ms)
ℹ tests 2
ℹ suites 0
ℹ pass 0
ℹ fail 1
ℹ cancelled 1
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5112.349013

✖ failing tests:

test at broken/retry.test.ts:5:1
✖ retries with backoff and succeeds on the third try, without waiting in real time (3.171061ms)
  Error: failed after 3 attempts
    [cause]: Error: flaky
  }

test at broken/retry.test.ts:21:1
✖ keeps the last error as the cause (5002.369341ms)
  'test timed out after 5000ms'

Two failures, two different lessons:

  1. callCount() doesn't include the call in progress. Inside the mock, the first call sees 0, the second 1 and the third 2, so callCount() < 3 threw on all three attempts and retry gave up. Check the count outside the mock, or keep your own counter.
  2. The global mock leaked into the next test. When the first test failed on assert.equal, it never reached mock.timers.reset(). Fake timers stayed on, so the second test's real 1 ms backoff setTimeout never fired, and that test hung until the 5-second --test-timeout cancelled it. One failing test made an unrelated passing test look broken. Without --test-timeout, the whole run would have hung forever, which is exactly what my first attempt did.

The fixed version uses the test context's t.mock, which the runner resets automatically when each test ends, whether it passes or fails:

import { it } from "node:test";
import assert from "node:assert/strict";
import { retry } from "../src/retry.ts";

it("retries with backoff and succeeds on the third try, without waiting in real time", async (t) => {
  t.mock.timers.enable({ apis: ["setTimeout"] });     // t.mock is reset automatically when this test ends
  let calls = 0;
  const fn = t.mock.fn(async () => {
    calls++;
    if (calls < 3) throw new Error("flaky");
    return "ok";
  });
  const p = retry(fn, 3, 100);
  for (let i = 0; i < 2; i++) {                       // let each failure settle, then jump the clock past its backoff
    await new Promise(setImmediate);
    t.mock.timers.tick(100 * 2 ** i);
  }
  assert.equal(await p, "ok");
  assert.equal(fn.mock.callCount(), 3);
});

it("keeps the last error as the cause", async () => {
  const err = await retry(async () => { throw new Error("db down"); }, 2, 1).catch((e) => e);
  assert.match(err.message, /failed after 2 attempts/);
  assert.equal(err.cause.message, "db down");
});

That's what's in the six-test run above: the retry test took 6 ms, despite exercising 300 ms of backoff. Two habits to take from this: always use t.mock rather than the global mock, and always run with --test-timeout in CI.

Coverage, and What 100% Doesn't Mean

ℹ start of coverage report
ℹ ----------------------------------------------------------
ℹ file      | line % | branch % | funcs % | uncovered lines
ℹ ----------------------------------------------------------
ℹ src       |        |          |         | 
ℹ  money.ts | 100.00 |    86.67 |  100.00 | 
ℹ  retry.ts | 100.00 |   100.00 |  100.00 | 
ℹ ----------------------------------------------------------
ℹ all files | 100.00 |    90.91 |  100.00 | 
ℹ ----------------------------------------------------------
ℹ end of coverage report

That run had --test-coverage-lines=95, which fails the run if line coverage drops below 95%, and it passed with 100% line coverage. But look at the branch column: money.ts is at 86.67%. None of my tests passes an empty ratio list or ratios that sum to zero, so those two guard clauses have never run. They sit on lines that ran, so line coverage counts them as covered. Branch coverage is the honest number, and even 100% branch coverage only proves a line executed, not that a test checked its result. The Node docs still mark coverage as experimental, so treat the exact numbers as useful rather than authoritative.

How Fast Is It? Same 500 Tests, Three Runners

I generated the same 500 tests (10 files × 50 tests, plain .mjs) for each runner and timed five runs of each inside one node:26-slim container:

node v26.13.1, vitest 5.1.1, jest 30.5.2
node --test                          median   786 ms  (runs: 786 817 834 766 765)
vitest run                           median  1645 ms  (runs: 1836 1640 1645 1572 1667)
jest (ESM, vm-modules)               median  1240 ms  (runs: 1546 1240 1242 1175 1233)
Tests:       500 passed, 500 total

All three ran all 500 tests:

ℹ tests 500
ℹ pass 500
ℹ fail 0
 Test Files  10 passed (10)
      Tests  500 passed (500)
Test Suites: 10 passed, 10 total
Tests:       500 passed, 500 total
Runner Median wall time Install
node --test (Node 26.13.1) 786 ms nothing
Jest 30.5.2 (ESM via --experimental-vm-modules) 1,240 ms one dev dependency, plus its tree
Vitest 5.1.1 1,645 ms one dev dependency, plus its tree

node:test was about twice as fast as Vitest and 1.6x faster than Jest on this suite, mostly because there's no framework to boot and no transform pipeline. That's a startup-dominated benchmark, though. These tests take microseconds each, so it mainly measures overhead. On a suite with heavy tests, the per-test work dominates and the runners get closer. The npm install also printed a warning that Vitest's dependency tree includes a package with an install script (@parcel/watcher, running node-gyp rebuild), which node:test avoids by having no dependencies at all.

We recommend reading What is TypeScript? Why I Finally Stopped Fighting the Type System to continue reading our selection of content. The tests above are TypeScript running with no build step, and this covers why the types are worth having.

What is TypeScript? Why I Finally Stopped Fighting the Type System What TypeScript is and why it's worth it: static types on top of JavaScript, the bugs they catch, and how to adopt them without fighting the compiler. SudoSecurity · Santhdium

When to Use Something Else

node:test isn't the right tool everywhere:

  • Frontend components. Vitest's browser mode and jsdom integration, and Testing Library's ecosystem, are built around bundlers and DOM environments that node:test doesn't provide.
  • Projects that rely on bundler features. Vitest runs tests through Vite's transform pipeline, so path aliases, JSX and CSS imports work the same in tests as in the app.
  • Teams with a big Jest suite. Migrating thousands of jest.fn() calls is real work, and 400 ms per run doesn't pay for it.

For backend services, libraries, CLIs and scripts, the built-in runner is now a reasonable default, and it's one less dependency tree to audit and keep patched.

Exercises

  1. Close the branch gap. Add tests until money.ts shows 100% branch coverage. Which inputs did you need?
  2. Break it on purpose. Change allocate so the leftover cent goes to the last share. Which tests fail, and does the snapshot catch it before the property test does?
  3. Test the shutdown handler from part 1. Use t.mock.method(process, "exit") to test that a second SIGTERM exits immediately without actually exiting.
  4. Test the floating promise from part 2. Write a test that fails if signup() leaves a rejected promise unhandled. Hint: listen for unhandledRejection inside the test and use t.after() to clean up.
  5. CI config. Write the CI step: node --test --test-timeout=10000 --experimental-test-coverage --test-coverage-branches=90, and make it fail on purpose once to see the output.

What This Doesn't Cover

  • Integration and end-to-end testing. Spinning up a real database (Testcontainers) or a browser (Playwright) is a separate topic.
  • Property-based testing libraries. The loop in "always sums back to the total" is a hand-rolled property test. fast-check does this properly, with shrinking.
  • Bun and Deno test runners. Both have built-in runners with Jest-like APIs.
  • Test reporters for CI. --test-reporter=junit and friends exist and work. Pick the one your CI system displays.

The Actual Point

Node 26 ships a test runner good enough for most backend code: structure, assertions, mocks, fake timers, snapshots, coverage and watch mode, with TypeScript tests running directly and nothing to install. On my 500-test suite it was twice as fast as Vitest. The mistakes worth learning from aren't about the tool, though. Use t.mock, so a failing test can't break the next one, always set --test-timeout, read branch coverage instead of line coverage, and write the property test before the snapshot. Then the next two parts of this series have something to stand on.

Sources: the Node.js v26 node:test documentation (stability markers for snapshots and coverage), and the vitest and jest packages at the versions printed above. Every test, benchmark and output was run by me on node:26-slim. All code blocks are reproduced verbatim from the test files and runs, including the intentionally broken first attempt; the modules under test are original teaching code.

$ tail -f /forums

Discussion

Comments live on the community forums — sign in there to reply.