~7 min read • Updated Dec 22, 2025
1. Strict Assertion Mode
In strict mode, non-strict methods behave like their strict counterparts. For example, assert.deepEqual() behaves like assert.deepStrictEqual(). Error messages include detailed diffs between values.
const assert = require('node:assert/strict');
assert.deepEqual([1], ['1']);
// Throws AssertionError with detailed diff
Colors in diffs can be disabled using the NO_COLOR or NODE_DISABLE_COLORS environment variables.
2. Legacy Assertion Mode
Legacy mode uses the == operator for comparisons, which can produce unexpected results.
const assert = require('node:assert');
// WARNING: This does not throw an error!
assert.deepEqual(/a/gi, new Date());
3. The AssertionError Class
All errors thrown by the assert module are instances of AssertionError, which extends Error. Key properties include:
actual: the actual valueexpected: the expected valueoperator: the comparison operatorcode: alwaysERR_ASSERTIONgeneratedMessage: indicates if the message was auto-generated
4. The Assert Class
The Assert class allows creation of independent assertion instances with custom options.
Options:
diff: controls diff verbosity (simpleorfull)strict: enables strict modeskipPrototype: ignores prototype comparison in deep equality
const { Assert } = require('node:assert');
const assertInstance = new Assert({ diff: 'full' });
assertInstance.deepStrictEqual({ a: 1 }, { a: 2 });
Note: destructuring methods from an Assert instance loses custom configuration.
5. Core Methods
assert(value[, message])
Checks if a value is truthy. Alias of assert.ok().
assert.deepEqual()
Legacy comparison using ==. May yield surprising results. In strict mode, it is equivalent to assert.deepStrictEqual().
assert.deepStrictEqual()
Performs strict deep equality using Object.is(), comparing prototypes and type tags.
const assert = require('node:assert/strict');
// Fails because 1 !== '1'
assert.deepStrictEqual({ a: 1 }, { a: '1' });
6. Comparison Details
- Primitive values: legacy uses
==, strict usesObject.is() - Prototypes: ignored in legacy, compared in strict
- Symbols: compared in strict
- Map/Set: keys and items compared unordered
- WeakMap/WeakSet: equal only if referencing the same instance
- RegExp: source and flags always compared
Conclusion
The assert module is a powerful tool for testing and validation in Node.js. By choosing strict mode and leveraging AssertionError and Assert, developers can ensure precise, predictable results. Best practice is to use strict mode for reliable comparisons and clearer error messages.
1. assert.doesNotMatch(string, regexp[, message])
Ensures that the input string does not match the given regular expression.
const assert = require('node:assert/strict');
assert.doesNotMatch('I will fail', /fail/); // Error
assert.doesNotMatch('I will pass', /different/); // OK
If the string matches or is not of type string, an AssertionError is thrown.
2. assert.doesNotReject(asyncFn[, error][, message])
Ensures that a Promise or async function does not reject.
await assert.doesNotReject(Promise.resolve('ok')); // OK
await assert.doesNotReject(Promise.reject(new Error('fail'))); // Error
Behaves like assert.doesNotThrow() but for asynchronous code.
3. assert.doesNotThrow(fn[, error][, message])
Ensures that the given function does not throw an error.
assert.doesNotThrow(() => { /* safe code */ }); // OK
assert.doesNotThrow(() => { throw new TypeError('Wrong'); }, TypeError);
// AssertionError: Got unwanted exception
If the function throws and the error matches the specified type, an AssertionError is raised.
4. assert.equal(actual, expected[, message])
In legacy mode, compares values using ==. In strict mode, it is an alias of assert.strictEqual().
const assert = require('node:assert');
assert.equal(1, '1'); // OK in legacy mode
assert.equal(NaN, NaN); // OK
assert.equal(1, 2); // Error
5. assert.fail([message])
Always throws an error. The message can be customized.
assert.fail(); // AssertionError: Failed
assert.fail('boom'); // AssertionError: boom
assert.fail(new TypeError('need array')); // TypeError
6. assert.ifError(value)
Throws the value if it is not null or undefined. Useful for checking error arguments in callbacks.
assert.ifError(null); // OK
assert.ifError('error'); // AssertionError: got unwanted exception
7. assert.match(string, regexp[, message])
Ensures that the input string matches the given regular expression.
assert.match('I will pass', /pass/); // OK
assert.match('I will fail', /pass/); // Error
8. assert.notDeepEqual(actual, expected[, message])
Ensures that two values are not deeply equal. Opposite of assert.deepEqual().
const obj1 = { a: { b: 1 } };
const obj2 = { a: { b: 2 } };
assert.notDeepEqual(obj1, obj2); // OK
assert.notDeepEqual(obj1, obj1); // Error
Conclusion
The advanced methods of the assert module provide fine-grained control for testing complex scenarios. Functions like doesNotMatch, doesNotReject, doesNotThrow, and ifError make it easier to validate code paths and ensure predictable behavior. Using these methods helps create clearer, more reliable tests in Node.js applications.
1. assert.notDeepStrictEqual(actual, expected[, message])
Tests that two values are not deeply and strictly equal. Opposite of assert.deepStrictEqual().
const assert = require('node:assert/strict');
assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); // OK
If the values are deeply and strictly equal, an AssertionError is thrown.
2. assert.notEqual(actual, expected[, message])
In legacy mode, compares values using the != operator. In strict mode, it is an alias of assert.notStrictEqual().
const assert = require('node:assert');
assert.notEqual(1, 2); // OK
assert.notEqual(1, 1); // Error
assert.notEqual(1, '1'); // Error in legacy mode
3. assert.notStrictEqual(actual, expected[, message])
Tests that two values are not strictly equal, using Object.is().
const assert = require('node:assert/strict');
assert.notStrictEqual(1, 2); // OK
assert.notStrictEqual(1, 1); // Error
assert.notStrictEqual(1, '1'); // OK
4. assert.ok(value[, message])
Tests if a value is truthy. Equivalent to assert.equal(!!value, true).
const assert = require('node:assert/strict');
assert.ok(true); // OK
assert.ok(1); // OK
assert.ok(false, 'it\'s false'); // Error with custom message
assert.ok(); // Error: No value argument passed
Note: In the REPL, error messages differ slightly from those thrown in files.
5. assert.rejects(asyncFn[, error][, message])
Tests that a Promise or async function rejects. Similar to assert.throws() but for asynchronous code.
const assert = require('node:assert/strict');
(async () => {
await assert.rejects(
async () => { throw new TypeError('Wrong value'); },
{ name: 'TypeError', message: 'Wrong value' }
);
})();
The error parameter can be a class, RegExp, validation function, or object. If a string is passed as the second argument, it is treated as the message, not the error type.
Conclusion
The assert module in Node.js is a powerful tool for testing and validation. Methods like notDeepStrictEqual, notEqual, notStrictEqual, ok, and rejects provide precise control over different testing scenarios. Using them correctly ensures clearer, more reliable tests and easier debugging.
1. assert.strictEqual(actual, expected[, message])
Tests strict equality between two values using Object.is().
const assert = require('node:assert/strict');
assert.strictEqual(1, 2);
// AssertionError: 1 !== 2
assert.strictEqual(1, 1);
// OK
assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError with detailed diff
const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// Custom error message
assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// Throws custom TypeError
If values are not strictly equal, an AssertionError is thrown. If the message is an Error instance, that error is thrown instead.
2. assert.throws(fn[, error][, message])
Expects the given function to throw an error.
Error validation options:
- A class (e.g.,
Error) - A
RegExpto match the error message - A validation function returning
true - A validation object or error instance with properties to check
const assert = require('node:assert/strict');
assert.throws(() => { throw new Error('Wrong value'); }, Error); // OK
assert.throws(() => { throw new Error('Wrong value'); }, /^Error: Wrong value$/); // OK
assert.throws(
() => { throw new Error('Wrong value'); },
(err) => {
assert(err instanceof Error);
assert(/value/.test(err));
return true;
},
'unexpected error',
);
Note: Avoid using a string as the second argument, as it can cause ambiguous errors.
3. assert.partialDeepStrictEqual(actual, expected[, message])
Tests for partial deep equality. Only properties present in the expected object are compared. Behaves as a superset of assert.deepStrictEqual().
const assert = require('node:assert');
assert.partialDeepStrictEqual({ a: { b: { c: 1 } } }, { a: { b: { c: 1 } } }); // OK
assert.partialDeepStrictEqual({ a: 1, b: 2, c: 3 }, { b: 2 }); // OK
assert.partialDeepStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 5, 8]); // OK
assert.partialDeepStrictEqual(new Set([{ a: 1 }, { b: 1 }]), new Set([{ a: 1 }])); // OK
assert.partialDeepStrictEqual(new Map([['key1','value1'], ['key2','value2']]), new Map([['key2','value2']])); // OK
assert.partialDeepStrictEqual(123n, 123n); // OK
assert.partialDeepStrictEqual({ a: 1 }, { a: 1, b: 2 }); // Error
assert.partialDeepStrictEqual({ a: { b: 2 } }, { a: { b: '2' } }); // Error
This method is useful when you want to validate only part of a data structure without requiring full equality.
Conclusion
The assert module in Node.js is a powerful tool for writing reliable tests. Methods like strictEqual, throws, and partialDeepStrictEqual provide fine-grained control over equality checks, error validation, and partial comparisons. Using them correctly ensures clearer, more predictable test results.
Written & researched by Dr. Shahin Siami