Assertions and the node:test runner

A test is an assertion: a line that says what a function should answer and fails loudly when it does not. Node.js ships both halves of that, with nothing to install and no package from npm: node:assert compares values and throws an AssertionError when they differ, and node:test finds the tests in a file, runs them and reports the result.

The lesson takes the assertions first, because they are the part a test is made of: the strict module, the difference between a loose comparison and a deep one, and the check that a function throws what it should. The runner comes last, with the one command that matters and the exit code that a pipeline reads.

node:assert/strict

import assert from 'node:assert/strict' is the module to use. Each method throws an AssertionError with a message that shows both values, and error.code is ERR_ASSERTION, which is how a runner tells a failed check from an error of the code under test.

The file assert.mjs:

import assert from 'node:assert/strict'; const sum = (values) => values.reduce((total, value) => total + value, 0); assert.equal(sum([1, 2, 3]), 6); assert.deepEqual({ a: 1 }, { a: 1 }); assert.ok(sum([]) === 0); console.log('three checks passed'); try { assert.equal(sum([1, 2]), 4); } catch (error) { console.log('the failure:', error.name); console.log('the message starts with:', error.message.split('\n')[0]); console.log('the code:', error.code); }

node assert.mjs

three checks passed
the failure: AssertionError
the message starts with: Expected values to be strictly equal:
the code: ERR_ASSERTION

The three good checks printed nothing at all, which is the habit to build: a passing assertion is silent, and only a failure writes. The message is the first line of a block that shows the two values and the place in the file, and the code is the same for every failed assertion, whatever the method.

Loose, strict and deep

The default module keeps the loose comparison of the language, so assert.equal(1, '1') passes there, while assert/strict makes equal the same as strictEqual. For objects, deepEqual compares the contents rather than the identity, and it is the method a test of a data structure needs.

The file compare.mjs:

import assert from 'node:assert'; import strict from 'node:assert/strict'; assert.equal(1, '1'); console.log('the loose module accepts 1 == "1"'); try { strict.equal(1, '1'); } catch (error) { console.log('the strict module refuses it:', error.code); } strict.deepEqual({ a: [1, 2] }, { a: [1, 2] }); console.log('deepEqual compares the contents, not the identity'); try { strict.deepEqual({ a: [1, 2] }, { a: [1, 3] }); } catch (error) { console.log('a different value fails:', error.message.split('\n')[0]); }

node compare.mjs

the loose module accepts 1 == "1"
the strict module refuses it: ERR_ASSERTION
deepEqual compares the contents, not the identity
a different value fails: Expected values to be strictly deep-equal:

The same comparison passed in one module and failed in the other, which is why a test file imports node:assert/strict and never the plain one. The deep check walked into the arrays: two objects with the same contents pass, and one number makes it fail.

Asserting a throw

A function that must refuse bad input is tested with assert.throws, which takes the call as a function so that it can catch what comes out. The second argument may be the class the error must belong to or a pattern its message must match, and the two together say both what was thrown and why. assert.doesNotThrow is the opposite check.

The file throws.mjs:

import assert from 'node:assert/strict'; function parse(text) { const value = Number(text); if (Number.isNaN(value)) { throw new TypeError(`not a number: ${text}`); } return value; } assert.throws(() => parse('x'), TypeError); assert.throws(() => parse('x'), /not a number: x/); assert.doesNotThrow(() => parse('4')); console.log('the throw matches the class and the pattern'); console.log('the value:', parse(' 4 ')); try { assert.throws(() => parse('4')); } catch (error) { console.log('a call that does not throw fails the check:', error.name); }

node throws.mjs

the throw matches the class and the pattern
the value: 4
a call that does not throw fails the check: AssertionError

A call that returns instead of throwing fails the check, so the assertion holds both halves of the contract. The value line is there because Number reads the spaces away, which is the sort of detail a test pins down before it becomes a bug report.

The node:test runner

node:test gives a file the shape of a test suite: test takes a name and a function, and a failed assertion inside the function fails that test and nothing else. The runner finds the file, runs the tests one after another and sets the exit code, which is what a pipeline reads.

The file test.mjs:

import assert from 'node:assert/strict'; import { test } from 'node:test'; function money(cents) { return `$${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, '0')}`; } test('money adds two decimals', () => { assert.equal(money(500), '$5.00'); }); test('money pads a small amount', () => { assert.equal(money(5), '$0.05'); }); test('money handles zero', () => { assert.equal(money(0), '$0.00'); });

node --test-reporter=dot test.mjs
echo "exit code: $?"

...
exit code: 0

Three dots, one per test, and a zero for the shell. The default reporter prints a line with the name of each test and how long it took, and this page runs the same file through the dot reporter because a duration is a different number on every run and the block above would never match it. A failing test prints a cross in place of a dot, the runner prints the assertion that failed, and the exit code becomes one.

Exercises

  1. Add a test for a negative amount to money. What does the function print, and does the test show it?
  2. Change one expected value in the test file and run it with the default reporter. Which test fails, and what is the exit code?
  3. Replace assert.equal with assert.deepEqual in the first program and run it again. Which check changes its result?
  4. Write a test for a function that must throw on an empty name, using assert.throws with a pattern.
  5. Count the tests in the file with test('...') and run it with --test-reporter=dot. How many dots do three tests print?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Where does node:assert come from?

    Answer

    It is part of Node.js and needs no install

    The module ships with the runtime, so a test file needs no dependency to use it.

  2. What does assert/strict change about assert.equal?

    Answer

    It compares with === instead of ==

    The strict module makes the loose methods strict, so 1 and "1" are no longer equal.

  3. What does assert.deepEqual compare?

    Answer

    The contents, key by key

    Two different objects with the same contents pass, which is what a test of data needs.

  4. What happens when an assertion fails?

    Answer

    It throws an AssertionError

    The failure is a throw, so the line after the assertion does not run.

  5. What does this program print? import assert from "node:assert/strict"; assert.equal(2 + 2, 4); console.log("after");

    Answer

    after

    The assertion passes silently and the next line runs.

  6. What does this program print? import assert from "node:assert/strict"; try { assert.deepEqual({ a: 1 }, { a: 2 }); } catch (error) { console.log(error.name); }

    Answer

    AssertionError

    A failed deep check throws an AssertionError, and the catch prints its name.

  7. What does this program print? import assert from "node:assert/strict"; assert.throws(() => { throw new RangeError("low"); }, RangeError); console.log("the check passed");

    Answer

    the check passed

    The call threw the class the check expects, so the assertion passes.

  8. What does this program print? import assert from "node:assert"; assert.equal("1", 1); console.log("loose");

    Answer

    loose

    The default module compares loosely, so the string and the number are equal there.

  9. What does a test file need to give the tests names and run them?

    Answer

    test from node:test around each function

    The runner reads the test calls, and the import is the only setup the file needs.

  10. What exit code does a run with a failing test leave?

    Answer

    1

    The runner marks the failure with a nonzero code, and one is the value it uses.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev