Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 133 ยท Testing

The assert Module

Learn the Node.js assert module - assert/strict, strictEqual, deepStrictEqual, throws, rejects, match, custom messages and how to read an AssertionError diff.

An assertion is a statement that must be true for your program to be correct. If it is true, nothing happens and the program continues. If it is false, the assertion throws an error that says exactly what was expected and what was found. Assertions are the heart of every automated test, and Node.js ships with a complete set of them in the built-in node:assert module. You do not need to install anything.

This lesson teaches you to pick the right assertion, to read the error it throws, and to avoid the traps of the older "loose" mode. The assertions work anywhere, in a plain script or inside the built-in test runner, which is where you will use them most.

Always import the strict version

The module exists in two flavors, and the difference matters. In legacy mode (node:assert), methods like assert.equal() compare with the loose == operator, so 1 equals '1' and 0 equals false. That hides bugs. In strict mode (node:assert/strict) the same method names use the strict, predictable comparisons. Always import the strict one:

NODE
import assert from 'node:assert/strict';

You can also write import { strict as assert } from 'node:assert', which gives the same object. In strict mode, assert.equal is an alias of assert.strictEqual, and assert.deepEqual is an alias of assert.deepStrictEqual. This lesson uses the explicit long names so the code reads the same in both worlds.

Node.js Strict versus loose equality

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 legacy module quietly accepted two comparisons that are almost certainly mistakes. The strict one rejects them with a clear message.

The everyday assertions

A handful of methods cover about ninety percent of tests.

Method Passes when
assert.ok(value) or assert(value) value is truthy
assert.strictEqual(actual, expected) the two are identical (Object.is rules)
assert.notStrictEqual(a, b) the two are not identical
assert.deepStrictEqual(actual, expected) the two have equal contents, recursively, with equal prototypes
assert.notDeepStrictEqual(a, b) the two differ somewhere in their contents
assert.throws(fn, expected) calling fn throws a matching error
assert.rejects(promiseOrFn, expected) the promise rejects with a matching error
assert.match(string, regexp) the string matches the pattern
assert.fail(message) never; it always fails

Remember the argument order: actual first, expected second. Getting it backwards still works but the diff in the error message will read the wrong way round.

strictEqual compares primitives by value and objects by identity. Two different arrays with the same items are not strictly equal, because they are two objects. For contents, you need deepStrictEqual.

Node.js strictEqual compares identity, deepStrictEqual compares contents

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.

strictEqual uses Object.is() semantics. That means NaN equals NaN, and 0 and -0 are different. This is usually what you want in a test, and it is a small surprise if you are used to ===.

Reading an AssertionError

When an assertion fails, it throws an AssertionError. Besides a readable message it carries machine-readable fields: actual, expected, operator (the check that failed), and code, which is always 'ERR_ASSERTION'. The message for object comparisons is a diff: lines starting with + exist only in the actual value, and lines starting with - exist only in the expected value.

Node.js A deepStrictEqual diff (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 uncaught error prints the diff and a stack trace pointing at main.mjs. Find the line that begins with + (what your code produced) and the line with - (what the test expected). The diff lists keys in sorted order, not in the order you wrote them. Here the actual array contains 'editor' where the test wanted 'viewer', and everything else is shown as unchanged context. In a big object the diff saves you from hunting for the one differing field.

You can also catch the error and inspect it, which is useful when you want to build your own test tooling:

Node.js Inspecting the fields of an AssertionError

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.

generatedMessage is true when Node wrote the message and false when you supplied your own.

Custom messages

Every assertion accepts a final message argument. Use it when the default wording would not tell a reader what went wrong in terms of your program. You can pass a string or an Error object; with an error object, that exact error is thrown instead of an AssertionError.

NODE
import assert from 'node:assert/strict';

assert.ok(user.isAdmin, 'only admins may delete projects');
assert.strictEqual(cart.items.length, 2, 'cart should hold two items after merge');

Do not overuse this. For simple comparisons the generated diff is usually clearer than a hand-written sentence, and a stale message can mislead. Reach for a custom message when the value alone is not self-explanatory, for example inside a loop where you need to know which iteration failed.

Asserting that code throws

assert.throws(fn, expected) calls fn and passes only if it throws. The second argument describes the error you expect, and there are four useful shapes:

  • a class: the error must be an instance of it (TypeError);
  • a RegExp: tested against the error's string form (/must be positive/);
  • an object: each listed property must deep-equal the error's property ({ name: 'RangeError', message: 'too big' }; regular expressions as values are matched, not compared);
  • a function: called with the error; return true to accept (for anything else, throw or return false).

Always pass the second argument. A bare assert.throws(fn) passes for any error, including the typo-induced ReferenceError you did not intend to catch.

Node.js Four ways to describe the expected error

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.

Note that assert.throws wants a function, not the result of calling one. Writing assert.throws(setAge('x')) calls setAge first, the error escapes before throws even starts, and your test crashes in a confusing way. Wrap the call in an arrow function.

Asserting that a promise rejects

For asynchronous code the partner is assert.rejects(). It returns a promise, so you must await it (or return it from your test). It accepts either a promise or a function that returns one, and the same expected shapes as throws. Its mirror image, assert.doesNotReject(), passes when the promise fulfills.

Node.js assert.rejects with async code

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.

If you forget await, the assertion still runs but its failure becomes an unhandled rejection, possibly after your test has already been reported as passed. Treat a missing await before assert.rejects as a bug.

Matching text and patterns

assert.match(string, regexp) checks a string against a regular expression and prints both when it fails. assert.doesNotMatch() is the opposite. They beat assert.ok(/x/.test(s)) because the failure message shows the input.

NODE
import assert from 'node:assert/strict';

assert.match('order-2026-0042', /^order-\d{4}-\d{4}$/);
assert.doesNotMatch('hello', /\d/);

match requires a string as its first argument. Passing a number or an object fails with a different error saying the input must be a string.

Deep equality in detail

deepStrictEqual is smarter than a simple recursive check. It compares:

  • own enumerable properties, recursively;
  • prototypes, so a plain object never equals a class instance with the same fields;
  • Map and Set contents regardless of insertion order for sets and map keys;
  • Date values by time, RegExp by source and flags, and error objects by message and name;
  • typed arrays and Buffer contents;
  • symbol-keyed properties, and circular structures without looping forever.

It does not compare functions by anything other than identity, and it ignores non-enumerable properties (except the message and name of errors).

Node.js What deepStrictEqual does and does not accept

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 last three failures are the ones that bite in real projects. A class instance is never "just an object", and { a: undefined } is not {} because the first has an own property. Strictness here is a feature: it forces your function to return exactly the shape you promised.

Comparing outside of tests

Sometimes you want the yes/no answer without an exception. The node:util module has isDeepStrictEqual(a, b), which uses the very same algorithm and returns a boolean. Use it for application logic (for example, "has this config changed?"), and keep assert for checks that must hold.

Node.js util.isDeepStrictEqual returns a boolean

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.

You will meet more helpers like it in The util Module.

Assertions that help the type checker and the reader

assert.ok(value) also serves as a guard. When you write TypeScript (see Node.js with TypeScript), assert.ok(user) narrows user to a truthy type for the lines that follow. In plain JavaScript it still documents your assumption: this must not be null here. Use it inside application code sparingly, for conditions that mean a programmer made a mistake, and keep ordinary input validation as normal if checks that throw meaningful errors. The distinction between the two kinds of failure is covered in Error Handling in Production.

Two older methods deserve a warning label. assert.ifError(value) throws if value is not null or undefined; it exists for callback-style tests (assert.ifError(err) at the top of a callback) and has little use today. assert.deepEqual and assert.equal in legacy mode are the loose ones; if you see them in old tests, migrating to strict mode will usually reveal a few hidden bugs.

Pitfalls professionals know

  • Swapped arguments. assert.strictEqual(expected, actual) passes and fails identically, but the diff labels are reversed and you debug the wrong side. Keep the order.
  • Asserting on floating point. 0.1 + 0.2 is not 0.3. Compare with a tolerance: assert.ok(Math.abs(a - b) < 1e-9).
  • One giant assertion. A single deepStrictEqual on a 60-field object tells you what differs but not why. Assert the important fields on their own when the object is huge.
  • Asserting inside callbacks that swallow errors. If an assert runs inside a callback that is caught by a try/catch somewhere, the failure can vanish. In async code, prefer await and let errors propagate.
  • Using assert for user input. Assertions are for impossible states. Input validation needs friendly errors, not ERR_ASSERTION.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which import gives you strict comparisons for assert.equal?

    Only node:assert/strict makes equal behave like strictEqual and deepEqual like deepStrictEqual. The plain node:assert module keeps the legacy loose == comparison.
  2. 2. Two separate arrays, [1, 2] and [1, 2], are compared. Which assertion passes?

    strictEqual compares object identity, and two arrays are two objects. deepStrictEqual compares their contents, so it passes.
  3. 3. What is wrong with assert.throws(parse('{bad'))?

    assert.throws needs a function to call. Calling parse yourself throws before assert.throws starts, so the test crashes instead of passing.
  4. 4. You call assert.rejects(somePromise) without await. What can happen?

    assert.rejects returns a promise. Without await, a failed assertion rejects that promise with nobody listening, which is an unhandled rejection and can appear too late.
  5. 5. In a deepStrictEqual diff, what does a line starting with - mean?

    The header reads + actual - expected, so minus lines belong to the expected value and plus lines to the actual value.

Summary

  • Import node:assert/strict so equal and deepEqual mean the strict versions.
  • Put the actual value first and the expected value second.
  • strictEqual compares identity for objects; deepStrictEqual compares contents, prototypes and types.
  • assert.throws takes a function and a description of the error; assert.rejects takes a promise or function and must be awaited.
  • Read the + actual - expected diff in an AssertionError; its code is ERR_ASSERTION.
  • util.isDeepStrictEqual gives a boolean when you do not want an exception.
  • Use assertions for impossible states and tests, never for validating user input.

Next: Mocks, Spies and Fake Timers