Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 133 ยท Testing

The Built-in Test Runner

Learn the built-in Node.js test runner - test, describe and it, hooks, subtests, skip and todo, timeouts, reporters, running tests programmatically, coverage and watch mode.

Code you do not test is code you are afraid to change. For years, testing a Node.js project meant first choosing and installing a framework (Mocha, Jest, Ava, Tap). Since Node.js 18 there is a test runner built in: the node:test module and the node --test command. It needs no installation, no configuration file and no dependencies, it starts quickly, and it covers what most projects need: tests, suites, hooks, subtests, mocks, coverage and several report formats.

This lesson teaches node:test from the first test to the details of reporters. A test runner normally lives in your terminal, and the editor on this page cannot show a terminal, so the runnable examples use one trick: they write a small test file, run it through the runner's programmatic API (run()), and print the results in a stable, readable form. That is also a good way to learn how the runner works. The command-line parts (node --test, --watch, coverage) are shown as read-only text, as you would see on your machine.

Your first test

A test is a function that either finishes normally (pass) or throws (fail). You register it with test() and check values with the assert module (see The assert Module); assert/strict is the best choice because it uses strict comparisons everywhere.

MJS
// math.test.mjs   (read-only: run it with `node --test`)
import { test } from 'node:test';
import assert from 'node:assert/strict';

function add(a, b) {
  return a + b;
}

test('add sums two numbers', () => {
  assert.equal(add(2, 3), 5);
});

On your machine you would run node --test. With no arguments, Node searches the project for files named *.test.js, *.test.mjs, *.test.cjs, test-*.js, *-test.js and anything inside a test folder, runs each file in its own process, and prints a report. Exit code 0 means everything passed; any failure gives exit code 1, which is what CI systems look for.

Since we cannot call the command here, this helper does the same thing from code. It writes the source you give it to a file, runs it with run(), and prints one line per test. We keep the output free of timings, because durations differ on every run.

Node.js Run a passing and a failing test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first test passes quietly. The second throws an AssertionError because 2 is not 3, and the runner marks it as failed but keeps going: one broken test never stops the others. In a real terminal you would also see the message Expected values to be strictly equal: 2 !== 3 with a diff and the file and line.

The helper runTests is reused in the rest of the examples (each is self-contained, so you will see it again). Everything inside the backtick template string is the test file.

Grouping with describe and it

For larger code you group related tests in a suite. describe() creates a suite and it() creates a test inside it; it is simply an alias for test that reads well in a suite. If you know Mocha or Jest the style will feel familiar. Nesting suites is allowed.

Node.js Suites with describe and it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The report indents tests under their suite, which is what makes failures easy to locate: "Cart > with items > adds up prices". Choose names that read as sentences, so a failing line explains the broken behavior without opening the file.

Hooks: set up and tear down

Tests should be independent, but they often need the same preparation: a fresh object, a temporary folder, a database connection. Hooks run code around tests:

Hook Runs
before(fn) once, before the first test of the suite
after(fn) once, after the last test
beforeEach(fn) before every test
afterEach(fn) after every test, even when the test failed

Hooks can be async. Use beforeEach to create fresh state, so no test can be influenced by an earlier one, and use after/afterEach for cleanup (close servers, delete files). The order is easiest to see by logging.

Node.js The order in which hooks run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The pattern is before, then for each test beforeEach, test, afterEach, and finally after. A hook that throws makes the tests it guards fail, with an error that names the hook.

Tests in one file run one after another by default, so sharing a variable between tests works, but it makes tests depend on order. Prefer beforeEach to rebuild the state so each test can run alone.

Subtests with the test context

Every test function receives a test context, usually called t. Its t.test() method creates subtests, which is useful for data-driven tests: one loop, many named cases. Subtests must be awaited. The context also provides t.skip(), t.todo(), t.diagnostic(), t.plan() and t.mock (see Mocks, Spies and Fake Timers).

Node.js Data-driven subtests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When one case fails, its name tells you exactly which input was wrong, and the parent test is reported as failed too ("1 subtest failed") while the rest still run.

Skip, todo and only

Sometimes a test cannot run yet. Rather than deleting or commenting it out, mark it:

  • skip (test.skip(...), { skip: true } or { skip: 'needs Windows' }): the test does not run and is reported as skipped. Use it for tests that do not apply in this environment.
  • todo (test.todo(...), { todo: true }): documents work not done yet. A todo test that has a body is still run, and its failure does not fail the whole run.
  • only ({ only: true }, with node --test --test-only): run just the marked tests while you focus on one problem. Never commit it by accident; CI should run the full suite.
Node.js Skipped and todo tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the summary: the run counts as a success even though the todo test threw, because todo is a promise to fix it later. Use todo for known problems you want to keep visible, not as a place to hide failures.

Async tests, timeouts and failing on purpose

A test function may be async; the runner waits for the returned promise. Forgetting to await an assertion is the most common bug in async tests: the test finishes before the check runs, and passes for the wrong reason. Use assert.rejects to check that a promise fails.

Tests can also have a timeout (in milliseconds), so a hung test does not freeze the suite. By default there is no timeout, which means a forgotten promise that never settles ends the run only through the process exit.

Node.js Async tests and a timeout (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The third test is cancelled by its 30 ms timeout and reports "test timed out after 30ms". A timeout stops the runner from waiting; it does not stop the code, which is another reason to clean up timers and servers in after hooks.

Reporters: choosing how results look

A reporter turns the stream of test events into output. Built-in reporters:

Reporter Output
spec Readable tree with checkmarks (the default in a terminal)
dot One dot per test, compact for large suites
tap The TAP protocol, understood by many tools
junit XML for CI dashboards
lcov Coverage data for coverage services
Terminal
# Read-only: commands for your own terminal.
node --test --test-reporter=spec
node --test --test-reporter=junit --test-reporter-destination=report.xml
node --test --test-reporter=spec --test-reporter=junit --test-reporter-destination=stdout --test-reporter-destination=report.xml

Because durations are part of the standard reporters, their output changes on every run, which is why this lesson prints its own report. You can write a custom reporter as an async generator function that receives the event stream and yields text. The runner's compose() method plugs one in.

Node.js A custom reporter in 12 lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The check for details.type === 'suite' matters: a suite is reported as its own pass or fail event, and without that line the failing suite strings would be counted as a third failure.

Running the test runner programmatically

You have been using run() all along. It returns a stream of events and accepts options such as:

  • files: the files to run (default: discover them like the CLI),
  • concurrency: how many test files to run at once (false for one at a time, true for one per CPU core),
  • timeout: a default timeout for all tests,
  • only, testNamePatterns and testSkipPatterns: filter tests by name,
  • isolation: 'process' (default, a child process per file) or 'none' (everything in the current process),
  • coverage and watch: enable the features described next.

Programmatic runs are useful for custom build scripts, for IDE integrations, and, as here, for teaching.

Choosing which tests run

From the terminal you can narrow a run without editing code:

Terminal
node --test test/orders.test.mjs                     # one file
node --test --test-name-pattern="leap year"          # tests whose name matches
node --test --test-skip-pattern="slow"               # skip matching tests
node --test --test-only                              # only tests marked { only: true }
node --test --test-concurrency=4                     # four files in parallel
node --test --test-timeout=5000                      # default timeout

Because each file runs in its own process, files are isolated from each other. Global state, mocked modules or environment changes in one file cannot leak into another. The price is a little process startup time per file (tens of milliseconds), which is rarely a problem.

Code coverage

Coverage tells you which lines, branches and functions your tests executed. Node can collect it using V8's built-in coverage, with a flag:

Terminal
node --test --experimental-test-coverage
TEXT
# Read-only: sample of the report layout, the numbers depend on your project
# start of coverage report
# file             | line % | branch % | funcs % | uncovered lines
# src/cart.mjs     |  92.31 |    85.71 |  100.00 | 14-15
# test/cart.test.mjs | 100.00 |   100.00 |  100.00 |
# end of coverage report

You can set thresholds so CI fails when coverage drops (--test-coverage-lines=80, --test-coverage-branches=70) and include or exclude files with glob options. Treat coverage as a smoke detector rather than a goal. A line being executed does not mean its result was checked; 100% coverage with weak assertions finds no bugs. Use the report to discover code your tests never touch.

Watch mode

During development you want tests to rerun when you save a file:

Terminal
node --test --watch

The runner stays alive, watches the test files and the modules they import, and reruns only the affected files after each change. Combined with --test-name-pattern or { only: true }, you get a quick feedback loop with no extra tools. Watch mode is for your terminal, so it cannot run in our editor.

Practical advice

  • One behavior per test, named as a sentence. When a test fails, the name should tell you what broke.
  • Arrange, act, assert: set up the data, call the code, check the result. Keep each phase visible.
  • Do not depend on the clock, the network or randomness; inject them (see Project Structure and Architecture) or mock them.
  • Test behavior, not implementation. Tests that mirror the code line by line break on every refactor without catching bugs.
  • Always await async work in a test, and close servers, timers and files in after hooks, or the process will not exit.
  • Put tests next to the code (cart.test.mjs beside cart.mjs) or in a test/ folder; both are discovered automatically.
  • Add "test": "node --test" to package.json scripts so npm test works for everyone (see package.json in Depth).

You will meet the other pieces of the testing story next: The assert Module for the checks themselves, Mocks, Spies and Fake Timers for isolating code, Testing HTTP Servers and CLIs for whole-program tests, and the Test-Driven Development Workshop for putting it all into practice.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does a test in node:test fail?

    A test passes when it finishes without throwing. Any thrown error, including an AssertionError, or a rejected promise, marks it as failed.
  2. 2. In which order do hooks run for a suite with two tests?

    before and after run once for the suite, while beforeEach and afterEach wrap every single test.
  3. 3. What is a common mistake in async tests that makes them pass for the wrong reason?

    If the promise is not awaited or returned, the test function finishes first and the later failure is not attributed to it.
  4. 4. What happens when a test marked with the todo option throws?

    Todo tests document unfinished work. They run, and their failure is shown, but it does not count against the exit code.
  5. 5. Why does the lesson use run() with its own reporting instead of printing the default output?

    Standard reporters print timings, which vary from run to run, so a custom report gives stable output in the page editor.

Summary

  • node:test is built in: write tests with test(), group with describe() and it(), and run them with node --test; a test fails when it throws or rejects.
  • Use assert/strict for the checks, and always await asynchronous work.
  • Hooks (before, after, beforeEach, afterEach) set up and clean up; use beforeEach for fresh state.
  • The test context t provides subtests (t.test), skipping, todo notes and plans, which makes data-driven tests easy.
  • Mark tests with skip, todo or only; give long-running tests a timeout.
  • Reporters (spec, dot, tap, junit, lcov) format the results, and run() gives you the raw event stream for custom reporting.
  • Coverage (--experimental-test-coverage) and watch mode (--watch) round out the workflow; treat coverage as a hint, not a goal.

Next: The assert Module