Node.js Assert Module
The Node.js assert module provides a set of assertion functions for verifying invariants, most commonly used for writing tests that throw an error when a condition is not met.
What the Assert Module Is For
assert is a core Node.js module that offers simple functions to test whether a value is truthy, whether two values are equal, or whether a function throws. Unlike third-party testing frameworks, assert has no test runner or reporting built in - it simply throws an AssertionError when a check fails, which is why it pairs naturally with test frameworks that catch thrown errors to report failures.
The module exports both a default strict-mode object (require('assert').strict, or require('assert/strict')) and a legacy mode. In modern code you should always prefer strict mode, since legacy mode uses the loose == operator for equality methods, which leads to surprising type coercion bugs.
assert.strictEqual and assert.deepStrictEqual
assert.strictEqual(actual, expected[, message]) compares two values using Object.is(), which behaves like === except that it treats NaN as equal to NaN and distinguishes +0 from -0. If the values are not strictly equal, it throws an AssertionError showing both values in a diff-friendly format.
assert.strictEqual basics
const assert = require('assert');
function add(a, b) {
return a + b;
}
assert.strictEqual(add(2, 3), 5);
assert.strictEqual(add(-1, 1), 0);
try {
assert.strictEqual(add(2, 2), 5);
} catch (err) {
console.log(err.name); // AssertionError
console.log(err.message); // Expected values to be strictly equal
}Comparing objects with deepStrictEqual
const assert = require('assert');
const actual = { id: 1, tags: ['a', 'b'] };
const expected = { id: 1, tags: ['a', 'b'] };
// strictEqual would fail here since these are different object references
assert.deepStrictEqual(actual, expected);
console.log('Objects match structurally');Throwing on Failure and Testing for Errors
Every assertion function in the module throws a synchronous AssertionError as soon as a check fails - execution of the current function stops immediately. This is the entire mechanism the module relies on: there is no separate 'report and continue' mode. assert.throws() and assert.rejects() flip this around, letting you assert that a given function does throw or a given promise does reject, optionally checking the error type or message against a matcher.
- assert(value) or assert.ok(value) - throws if value is falsy
- assert.strictEqual(a, b) - throws unless Object.is(a, b) is true
- assert.deepStrictEqual(a, b) - throws unless a and b are structurally equal
- assert.throws(fn, error) - throws unless fn() throws an error matching error
- assert.rejects(asyncFn, error) - throws unless the returned promise rejects matching error
- assert.match(string, regexp) - throws unless string matches regexp
Asserting a function throws
const assert = require('assert');
function parsePositiveInt(input) {
const n = Number(input);
if (!Number.isInteger(n) || n <= 0) {
throw new RangeError('Input must be a positive integer');
}
return n;
}
assert.throws(
() => parsePositiveInt('-5'),
{ name: 'RangeError', message: 'Input must be a positive integer' }
);
assert.strictEqual(parsePositiveInt('42'), 42);
console.log('All checks passed');Using Assert Inside Tests
Because assert throws plain errors, it works seamlessly with Node's built-in test runner (node:test) as well as with third-party frameworks like Mocha or Jest, all of which catch thrown errors inside a test function and mark that test as failed. This makes assert a lightweight, dependency-free choice for writing unit tests in small scripts or libraries.
Exercise: Node.js Assert Module
What is the main purpose of the assert module?