For a long time, the first step in testing a Node.js project was choosing and installing a test framework: Jest, Mocha, Vitest, Ava. Each one brings its own dependencies, configuration and occasional fights with ES modules or TypeScript.

Node.js now ships with its own test runner. The node:test module gives you test functions, suites, hooks, mocking, fake timers and snapshot testing, and node --test finds and runs your test files. Coverage is built in too. For many projects, especially libraries, command-line tools and back-end services, that is everything you need, with nothing to install.

This article is for Node.js developers who want to try the built-in runner, or move a small project off Jest. We cover writing tests, running them, mocking, timers, snapshots and coverage, and finish with when you should still reach for a separate framework.

The examples assume a current LTS release, Node 24 or Node 26, and ES modules ("type": "module" in package.json).

Your first test

#

Create a small module to test:


_10
// src/price.js
_10
export function formatPrice(pence, currency = 'GBP') {
_10
if (!Number.isInteger(pence)) {
_10
throw new TypeError('pence must be an integer');
_10
}
_10
return new Intl.NumberFormat('en-GB', { style: 'currency', currency }).format(pence / 100);
_10
}

And a test file next to it:


_12
// src/price.test.js
_12
import { test } from 'node:test';
_12
import assert from 'node:assert/strict';
_12
import { formatPrice } from './price.js';
_12
_12
test('formats pence as pounds', () => {
_12
assert.equal(formatPrice(1999), '£19.99');
_12
});
_12
_12
test('throws on non-integer input', () => {
_12
assert.throws(() => formatPrice(19.5), TypeError);
_12
});

Run it:


_10
node --test

With no arguments, node --test searches the current directory for files that look like tests. The default patterns match files named like *.test.js, *-test.js, *_test.js, test-*.js and test.js, plus any .js, .cjs or .mjs file inside a test folder. You can also pass files or glob patterns yourself:


_10
node --test "src/**/*.test.js"

Quote the glob so Node expands it, not your shell, which keeps it working the same way on every platform.

Assertions

The runner does not include its own expect style API; it uses the node:assert module. Always import node:assert/strict, which makes equal and deepEqual use strict comparison. The most useful methods are:

  • assert.equal(actual, expected) and assert.notEqual for primitive values
  • assert.deepEqual(actual, expected) for objects and arrays
  • assert.ok(value) for truthiness
  • assert.throws(fn, expected) and assert.rejects(promise, expected) for errors
  • assert.match(string, regex) for patterns

Each test also gets a context object, usually called t, with the same assertions on t.assert.

Organising tests

#

Use describe and it if you like the familiar structure. They are aliases for suite and test.


_32
import { describe, it, beforeEach, afterEach } from 'node:test';
_32
import assert from 'node:assert/strict';
_32
import { Cart } from './cart.js';
_32
_32
describe('Cart', () => {
_32
let cart;
_32
_32
beforeEach(() => {
_32
cart = new Cart();
_32
});
_32
_32
afterEach(() => {
_32
cart = undefined;
_32
});
_32
_32
it('starts empty', () => {
_32
assert.equal(cart.items.length, 0);
_32
});
_32
_32
it('adds items', () => {
_32
cart.add({ sku: 'A1', price: 500 });
_32
assert.equal(cart.total(), 500);
_32
});
_32
_32
describe('discounts', () => {
_32
it('applies a percentage discount', () => {
_32
cart.add({ sku: 'A1', price: 1000 });
_32
cart.applyDiscount(10);
_32
assert.equal(cart.total(), 900);
_32
});
_32
});
_32
});

The hooks are before and after (once per suite) and beforeEach and afterEach (around each test).

Async tests

Return a promise or use an async function, and the runner waits for it:


_10
it('loads a user', async () => {
_10
const user = await getUser(1);
_10
assert.equal(user.name, 'Ada');
_10
});

If the promise rejects, the test fails with that error.

Skipping, todo and only


_10
it.skip('not ready yet', () => {});
_10
it.todo('handle refunds');
_10
it.only('the one I am debugging', () => {});

To run only tests marked with .only, pass --test-only. To run tests whose names match a pattern, use --test-name-pattern:


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

Watch mode

#

During development, add --watch and Node reruns the affected tests when you save a file:


_10
node --test --watch

Watch mode is still marked experimental, but it works well for day-to-day use.

Mocking functions and methods

#

The test context has a mock object. Mocks created through t.mock are restored automatically when the test finishes, so you do not need cleanup code.

Spying on a function

t.mock.fn() creates a function that records how it was called. Pass an implementation if you want it to do something:


_12
import { test } from 'node:test';
_12
import assert from 'node:assert/strict';
_12
import { notifyAll } from './notify.js';
_12
_12
test('calls send once per user', async (t) => {
_12
const send = t.mock.fn(async () => ({ ok: true }));
_12
_12
await notifyAll(['[email protected]', '[email protected]'], send);
_12
_12
assert.equal(send.mock.callCount(), 2);
_12
assert.deepEqual(send.mock.calls[0].arguments, ['[email protected]']);
_12
});

Each entry in mock.calls has arguments, result, error and this, so you can check what was passed in and what came back.

Replacing a method on an object

t.mock.method(object, name, implementation) replaces a method and tracks its calls:


_13
import { test } from 'node:test';
_13
import assert from 'node:assert/strict';
_13
import { db } from './db.js';
_13
import { getUserName } from './users.js';
_13
_13
test('reads the name from the database', async (t) => {
_13
t.mock.method(db, 'findUser', async (id) => ({ id, name: 'Ada' }));
_13
_13
const name = await getUserName(1);
_13
_13
assert.equal(name, 'Ada');
_13
assert.equal(db.findUser.mock.callCount(), 1);
_13
});

This works well when your code calls methods on a shared object. It does not help if your code imports a function directly with a named import, because you cannot replace a module's export from outside.

Mocking whole modules

For that case, there is mock.module(), which replaces what a module exports for any code that imports it afterwards:


_16
import { test } from 'node:test';
_16
import assert from 'node:assert/strict';
_16
_16
test('uses the mocked mailer', async (t) => {
_16
t.mock.module('./mailer.js', {
_16
namedExports: {
_16
sendEmail: async () => ({ id: 'test-id' }),
_16
},
_16
});
_16
_16
// Import after mocking so the mock is used
_16
const { signUp } = await import('./signup.js');
_16
const result = await signUp('[email protected]');
_16
_16
assert.equal(result.emailId, 'test-id');
_16
});

Module mocking is still experimental. It has required the --experimental-test-module-mocks flag, so check the test runner docs for your Node version before relying on it:


_10
node --test --experimental-test-module-mocks

If you find yourself mocking many modules, it is often a sign that passing dependencies in as arguments (as notifyAll does with send above) would make the code easier to test without any mocking tools at all.

Fake timers

#

Code that uses setTimeout, setInterval or Date is slow and flaky to test with real time. mock.timers replaces them with a clock you control:


_19
import { test } from 'node:test';
_19
import assert from 'node:assert/strict';
_19
import { debounce } from './debounce.js';
_19
_19
test('debounce waits before calling', (t) => {
_19
t.mock.timers.enable({ apis: ['setTimeout'] });
_19
const fn = t.mock.fn();
_19
const debounced = debounce(fn, 300);
_19
_19
debounced();
_19
debounced();
_19
assert.equal(fn.mock.callCount(), 0);
_19
_19
t.mock.timers.tick(299);
_19
assert.equal(fn.mock.callCount(), 0);
_19
_19
t.mock.timers.tick(1);
_19
assert.equal(fn.mock.callCount(), 1);
_19
});

Include 'Date' in the apis list to control the current time as well, and use t.mock.timers.setTime() to jump to a specific moment. runAll() fires every pending timer at once.

Snapshot testing

#

Snapshot tests save the output of some code the first time they run, then fail if it changes. They are handy for large outputs such as generated HTML or serialised objects.


_10
import { test } from 'node:test';
_10
import { renderEmail } from './email.js';
_10
_10
test('welcome email', (t) => {
_10
t.assert.snapshot(renderEmail({ name: 'Ada' }));
_10
});

The first run needs --test-update-snapshots to create the snapshot file; later runs compare against it. Rerun with the same flag when you have changed the output on purpose. Snapshot testing has been stable since Node 23.4, so it works without extra flags on current LTS releases.

Code coverage

#

Add --experimental-test-coverage and Node prints a coverage report after the tests:


_10
node --test --experimental-test-coverage

The report shows line, branch and function coverage for each file. Despite the flag name, it is reliable for everyday use; the experimental label means details may still change.

You can make the run fail if coverage drops below a threshold:


_10
node --test --experimental-test-coverage \
_10
--test-coverage-lines=90 \
_10
--test-coverage-branches=80 \
_10
--test-coverage-functions=90

And you can leave files out of the report:


_10
node --test --experimental-test-coverage \
_10
--test-coverage-exclude="**/*.test.js" \
_10
--test-coverage-exclude="scripts/**"

For CI tools that read LCOV files, use the lcov reporter and write it to a file, while keeping the readable spec output in the terminal:


_10
node --test --experimental-test-coverage \
_10
--test-reporter=spec --test-reporter-destination=stdout \
_10
--test-reporter=lcov --test-reporter-destination=lcov.info

Reporters

#

The default reporter is spec in a terminal, which prints a readable tree of results. Other built-in reporters are tap, dot, junit and lcov. junit is useful for CI systems that display test results from XML.

TypeScript

#

Current Node.js releases can run TypeScript files directly by stripping type annotations, and node --test includes .ts, .mts and .cts versions of the default patterns. So a file called price.test.ts is picked up and run with no build step.

Type stripping only removes types; it does not type check. Run tsc --noEmit separately in CI. It also does not support every TypeScript feature: syntax that needs code generation, such as enum and parameter properties, will not run without the separate transform option. Stick to erasable syntax in files you run this way.

A package.json setup

#

Putting it together, a typical set of scripts looks like this:


_10
{
_10
"type": "module",
_10
"scripts": {
_10
"test": "node --test",
_10
"test:watch": "node --test --watch",
_10
"test:coverage": "node --test --experimental-test-coverage --test-coverage-lines=90"
_10
}
_10
}

No dependencies, no config file.

Version support

#

The test runner has been marked stable since Node 20, and Node 20 has now reached end of life, so every supported release line (Node 22, 24 and 26) has it. Features have been added steadily, so newer releases are better:

  • Glob patterns for --test and the current default file patterns arrived in the Node 21 and 22 era.
  • Snapshot testing became stable in Node 23.4.
  • Coverage thresholds and include and exclude options are available in current releases.
  • Module mocking and coverage are still marked experimental.

If something in this article does not work on your version, check the test runner page in the Node.js docs for that exact release.

When not to use it

#
  • Front-end component tests. The runner has no DOM. You can add one with a library such as jsdom or happy-dom, but Vitest or a browser-based runner will be much less work for React or Vue components.
  • Projects that depend on bundler features. If your code relies on path aliases, CSS imports or other bundler transforms, a runner that shares your bundler's config (such as Vitest with Vite) will save a lot of setup.
  • Heavy use of module mocking. It works, but it is experimental. If your test suite relies on automatic mocking of many modules, as some Jest suites do, migrating will take real effort.
  • Large existing Jest suites that work fine. Migration has a cost. The built-in runner is best for new projects or small suites.

Wrapping up

#
  • node:test and node --test give you suites, hooks, async tests, watch mode and reporters with nothing to install.
  • Use node:assert/strict for assertions, and t.mock.fn() and t.mock.method() for spies and stubs that clean up after themselves.
  • t.mock.timers gives you fake timers, and t.assert.snapshot() gives you stable snapshot testing.
  • Add --experimental-test-coverage with threshold flags to enforce coverage in CI.
  • For DOM-heavy front-end tests or bundler-dependent code, a dedicated framework is still the better choice.

Further reading: Node.js docs: Test runner

file under:
Node.js

Was this article helpful?

About the author

Danny Engineering

A software engineer with a strong belief in human-centric design and driven by a deep empathy for users. Combining the latest technology with human values to build a better, more connected world.