This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Node.js assert Module Cheatsheet

A quick reference guide for the Node.js assert module: strict assertions, deep equality checks, exception throws, and error validation.

· Published

The built-in Node.js assert module provides an invariant-checking assertion framework for testing and runtime validations.

Always import assert/strict in modern Node.js to enforce strict equality (===):

const assert = require('assert/strict');
// or import assert from 'node:assert/strict';

Truthiness & Equality

// Truthiness check
assert(val, 'Expected value to be truthy');
assert.ok(val, 'Alias for assert()');

// Strict equality (===)
assert.equal(actual, expected);
assert.notEqual(actual, expected);

// Strict deep object equality
assert.deepEqual({ a: 1, b: [2] }, { a: 1, b: [2] });
assert.notDeepEqual({ a: 1 }, { a: 2 });

Error Handling & Exceptions

assert.throws()

Verifies that a function throws an expected error:

assert.throws(
  () => {
    throw new TypeError('Invalid parameter');
  },
  {
    name: 'TypeError',
    message: 'Invalid parameter'
  }
);

assert.doesNotThrow()

Verifies that a block runs without throwing an unhandled exception:

assert.doesNotThrow(() => {
  safeOperation();
});

Async Assertions

// Rejection verification for promises
await assert.rejects(
  async () => {
    await fetchInvalidUrl();
  },
  {
    name: 'TypeError'
  }
);

// Resolution verification for promises
await assert.doesNotReject(async () => {
  await fetchValidUrl();
});

References

Related topics