---
title: "Testing with Node's built-in test runner: node:test, mocking and coverage"
description: "Write and run tests with Node.js's built-in node:test module: suites, hooks, assertions, mocks, fake timers, snapshots and coverage, with no Jest required."
url: https://www.danny.engineering/article/testing-with-nodes-built-in-test-runner-nodetest-mocking-and-coverage
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:23:00.000Z
tags: ["Node.js"]
---

# Testing with Node's built-in test runner: node:test, mocking and coverage

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:


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


And a test file next to it:


```javascript
// src/price.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { formatPrice } from './price.js';

test('formats pence as pounds', () => {
  assert.equal(formatPrice(1999), '£19.99');
});

test('throws on non-integer input', () => {
  assert.throws(() => formatPrice(19.5), TypeError);
});
```


Run it:


```bash
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:


```bash
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`.


```javascript
import { describe, it, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { Cart } from './cart.js';

describe('Cart', () => {
  let cart;

  beforeEach(() => {
    cart = new Cart();
  });

  afterEach(() => {
    cart = undefined;
  });

  it('starts empty', () => {
    assert.equal(cart.items.length, 0);
  });

  it('adds items', () => {
    cart.add({ sku: 'A1', price: 500 });
    assert.equal(cart.total(), 500);
  });

  describe('discounts', () => {
    it('applies a percentage discount', () => {
      cart.add({ sku: 'A1', price: 1000 });
      cart.applyDiscount(10);
      assert.equal(cart.total(), 900);
    });
  });
});
```


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:


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


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


### Skipping, todo and only


```javascript
it.skip('not ready yet', () => {});
it.todo('handle refunds');
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`:


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


## Watch mode


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


```bash
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:


```javascript
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { notifyAll } from './notify.js';

test('calls send once per user', async (t) => {
  const send = t.mock.fn(async () => ({ ok: true }));

  await notifyAll(['a@example.com', 'b@example.com'], send);

  assert.equal(send.mock.callCount(), 2);
  assert.deepEqual(send.mock.calls[0].arguments, ['a@example.com']);
});
```


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:


```javascript
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { db } from './db.js';
import { getUserName } from './users.js';

test('reads the name from the database', async (t) => {
  t.mock.method(db, 'findUser', async (id) => ({ id, name: 'Ada' }));

  const name = await getUserName(1);

  assert.equal(name, 'Ada');
  assert.equal(db.findUser.mock.callCount(), 1);
});
```


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:


```javascript
import { test } from 'node:test';
import assert from 'node:assert/strict';

test('uses the mocked mailer', async (t) => {
  t.mock.module('./mailer.js', {
    namedExports: {
      sendEmail: async () => ({ id: 'test-id' }),
    },
  });

  // Import after mocking so the mock is used
  const { signUp } = await import('./signup.js');
  const result = await signUp('ada@example.com');

  assert.equal(result.emailId, 'test-id');
});
```


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:


```bash
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:


```javascript
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { debounce } from './debounce.js';

test('debounce waits before calling', (t) => {
  t.mock.timers.enable({ apis: ['setTimeout'] });
  const fn = t.mock.fn();
  const debounced = debounce(fn, 300);

  debounced();
  debounced();
  assert.equal(fn.mock.callCount(), 0);

  t.mock.timers.tick(299);
  assert.equal(fn.mock.callCount(), 0);

  t.mock.timers.tick(1);
  assert.equal(fn.mock.callCount(), 1);
});
```


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.


```javascript
import { test } from 'node:test';
import { renderEmail } from './email.js';

test('welcome email', (t) => {
  t.assert.snapshot(renderEmail({ name: 'Ada' }));
});
```


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:


```bash
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:


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


And you can leave files out of the report:


```bash
node --test --experimental-test-coverage \
  --test-coverage-exclude="**/*.test.js" \
  --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:


```bash
node --test --experimental-test-coverage \
  --test-reporter=spec --test-reporter-destination=stdout \
  --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:


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


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](https://nodejs.org/api/test.html)
