Comprehensive Guide to the Node.js Test Runner (node:test Module)

The node:test module is a built‑in, modern testing framework included directly in Node.js. . It supports synchronous, asynchronous, promise‑based, and callback‑style tests, along with subtests, hooks, mocking, snapshots, coverage, watch mode, and custom reporters. It is stable, powerful, and eliminates the need for external testing libraries for many projects.

node:testTestContext (t)SubtestsHooksMockingSnapshot testingCoverageWatch modeCustom reporters

~3 min read · Updated Dec 30, 2025

1. Importing the Module


const test = require('node:test');
// or ESM
import test from 'node:test';

2. Basic Test Types


The test runner supports all major styles of testing:


2.1 Synchronous Tests


test('Synchronous passing test', (t) => {
  assert.strictEqual(1, 1);
});

test('Synchronous failing test', (t) => {
  assert.strictEqual(1, 2);
});

2.2 Async & Promise Tests


test('Async passing test', async (t) => {
  assert.strictEqual(1, 1);
});

test('Async failing test', async (t) => {
  throw new Error('failed');
});

test('Promise failing test', (t) => {
  return Promise.reject(new Error('failed'));
});

2.3 Callback Tests


test('Callback passing test', (t, done) => {
  setImmediate(done);
});

test('Callback failing test', (t, done) => {
  setImmediate(() => done(new Error('failed')));
});

If any test fails, Node.js exits with code 1.


3. Subtests


Subtests allow grouping and structuring test suites:


test('Top level test', async (t) => {
  await t.test('Subtest 1', (t) => {
    assert.strictEqual(1, 1);
  });

  await t.test('Subtest 2', (t) => {
    assert.strictEqual(2, 2);
  });
});

4. Skipping & TODO Tests


test('Skipped test', { skip: true }, (t) => {});

test('Skipped with reason', { skip: 'reason' }, (t) => {});

test('TODO test', { todo: true }, (t) => {
  throw new Error('ignored failure');
});

// Inside a test:
t.skip('skip inside test');
t.todo('todo inside');

5. Only Tests


Run only specific tests:


test('Only this runs', { only: true }, (t) => {});

CLI:


node --test-only

Inside subtests:


t.runOnly(true);

6. Hooks


Hooks allow setup and teardown logic:


test('With hooks', async (t) => {
  t.before(() => console.log('Before all'));
  t.beforeEach(() => console.log('Before each'));
  t.afterEach(() => console.log('After each'));
  t.after(() => console.log('After all'));

  await t.test('Subtest 1', () => {});
  await t.test('Subtest 2', () => {});
});

7. Mocking


7.1 Mocking Functions


test('Mock function', (t) => {
  const fn = t.mock.fn((a, b) => a + b);
  assert.strictEqual(fn(2, 3), 5);
  assert.strictEqual(fn.mock.callCount(), 1);
});

7.2 Mocking Methods


test('Mock method', (t) => {
  const obj = { add: (a, b) => a + b };
  t.mock.method(obj, 'add');
  obj.add(1, 2);
  assert.strictEqual(obj.add.mock.callCount(), 1);
});

7.3 Mocking Timers & Date


test('Mock timers', (t) => {
  t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
  setTimeout(() => console.log('done'), 1000);
  t.mock.timers.tick(1000);
});

8. Snapshot Testing


test('Snapshot', (t) => {
  t.assert.snapshot({ a: 1, b: [2, 3] });
});

Update snapshots:


node --test-update-snapshots

9. Coverage


node --experimental-test-coverage --test-reporter=lcov

10. Watch Mode


node --test --watch

11. Custom Reporters


node --test --test-reporter=./my-reporter.js

12. Running Tests


node --test                        # run all tests
node --test test/**/*.test.js      # pattern
node --test-only                   # only { only: true }
node --test-name-pattern="my test" # filter by name

Conclusion


The node:test module is a powerful, built‑in test runner offering:

  • Simple and expressive API
  • Subtests and hooks
  • Mocking for functions, methods, timers, and modules
  • Snapshot testing
  • Coverage and watch mode
  • Custom reporters
  • Strict mode and test plans

It is a complete, modern testing solution for Node.js — with zero external dependencies.


Written & researched by Dr. Shahin Siami

Related Articles

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

Continue

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

Continue

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

Continue

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

Continue

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

Continue

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

Continue