assert
The assert module is an assertion utility built into Node.js for verifying program behavior. It throws an AssertionError when a condition is not met. It provides diverse verification methods such as assert.strictEqual, assert.deepStrictEqual, and assert.throws. Using the assert/strict module makes all methods operate in strict mode by default.
Basic Syntax
var assert = require('assert');
// Verify that a value is truthy
assert.ok(value);
// Verify that two values are strictly equal (equivalent to ===)
assert.strictEqual(actual, expected);
// Verify deep equality (compares contents of objects and arrays)
assert.deepStrictEqual(actual, expected);
// Verify that a function throws an exception
assert.throws(functionThatThrows, expectedErrorTypeOrCondition);
Main Methods
| Method | Description |
|---|---|
assert.ok(value) | Verifies that value is truthy. Fails for false, 0, null, undefined, empty string, and NaN. |
assert.strictEqual(actual, expected) | Verifies that actual and expected are equal using ===. Detects type differences. |
assert.notStrictEqual(actual, expected) | Verifies that actual and expected are not equal using !==. |
assert.deepStrictEqual(actual, expected) | Recursively compares the contents of objects and arrays, including property types, values, and order. |
assert.notDeepStrictEqual(actual, expected) | Verifies that the contents of objects or arrays are not equal. |
assert.throws(fn, error) | Verifies that an exception is thrown when fn is called. The second argument can specify an error type or regular expression. |
assert.doesNotThrow(fn) | Verifies that no exception is thrown when fn is called. |
assert.rejects(asyncFn) | Verifies that an async function is rejected. Returns a Promise. |
assert.doesNotReject(asyncFn) | Verifies that an async function is not rejected. |
assert.fail(message) | Unconditionally throws an AssertionError. Place it in code paths that should never be reached. |
assert.match(string, regexp) | Verifies that a string matches a regular expression (Node.js v13.6 and later). |
assert.ok / assert.strictEqual — Basic Verification
assert.ok() verifies that a value is truthy, while assert.strictEqual() verifies that two values are equal using ===. If verification fails, an AssertionError is thrown.
assert_basic.js
var assert = require('assert');
// Define the functions under test
var calcPower = function(base, multiplier) {
return base * multiplier;
};
var getName = function(id) {
var fighters = {
1: 'Yagami Iori',
2: 'Kusanagi Kyo',
3: 'Terry Bogard',
};
return fighters[id] || null;
};
// assert.ok: verify that a value is truthy
assert.ok(calcPower(100, 10)); // 1000 is truthy → passes
assert.ok(getName(1)); // 'Yagami Iori' is truthy → passes
// assert.strictEqual: verify equality using ===
assert.strictEqual(calcPower(100, 10), 1000); // passes
assert.strictEqual(getName(2), 'Kusanagi Kyo'); // passes
assert.strictEqual(getName(99), null); // null === null → passes
console.log('Basic tests: all passed');
// Failure examples (uncomment to trigger AssertionError)
// assert.strictEqual(calcPower(100, 10), 999);
// AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
// 1000 !== 999
node assert_basic.js Basic tests: all passed
assert.deepStrictEqual — Verifying Objects and Arrays
Objects and arrays are not equal via === because they have different references. assert.deepStrictEqual() recursively compares their contents, making it suitable for verifying objects with the same structure.
assert_deep.js
var assert = require('assert');
// Function under test: generates fighter data
var createFighter = function(name, team, power) {
return {
name: name,
team: team,
power: power,
isActive: true,
};
};
var sortByPower = function(fighters) {
return fighters.slice().sort(function(a, b) { return b.power - a.power; });
};
// Verify an object
var fighter = createFighter('Yagami Iori', 'Team Yagami', 9500);
assert.deepStrictEqual(fighter, {
name: 'Yagami Iori',
team: 'Team Yagami',
power: 9500,
isActive: true,
});
// Verify an array (order is also compared)
var sorted = sortByPower([
createFighter('Kusanagi Kyo', 'Team Kusanagi', 9200),
createFighter('Yagami Iori', 'Team Yagami', 9500),
createFighter('Terry Bogard', 'Team Buster Wolf', 8800),
]);
assert.strictEqual(sorted[0].name, 'Yagami Iori');
assert.strictEqual(sorted[1].name, 'Kusanagi Kyo');
assert.strictEqual(sorted[2].name, 'Terry Bogard');
// Verify element count
assert.strictEqual(sorted.length, 3);
console.log('deepStrictEqual tests: all passed');
node assert_deep.js deepStrictEqual tests: all passed
assert.throws — Testing Exceptions
Use assert.throws() to verify that a function throws an exception. The second argument accepts an error type, regular expression, or object to further verify the content of the thrown error.
assert_throws.js
var assert = require('assert');
// Function under test: validation with error handling
var registerFighter = function(name, power) {
if (typeof name !== 'string' || name.trim() === '') {
throw new TypeError('Name cannot be empty');
}
if (typeof power !== 'number' || power < 0) {
throw new RangeError('Power must be a non-negative number');
}
return { name: name, power: power };
};
// Verify that an error is thrown
assert.throws(
function() { registerFighter('', 1000); },
TypeError // Expect TypeError to be thrown
);
// Verify the error message as well (partial match using regex)
assert.throws(
function() { registerFighter('Shiranui Mai', -1); },
{ name: 'RangeError', message: /non-negative/ }
);
// Verify that no error is thrown
assert.doesNotThrow(function() {
var result = registerFighter('Ryo Sakazaki', 8500);
assert.strictEqual(result.name, 'Ryo Sakazaki');
});
console.log('throws tests: all passed');
node assert_throws.js throws tests: all passed
assert.rejects — Testing Asynchronous Operations
Use assert.rejects() to test Promise-based APIs. It verifies that an async function is rejected. It is commonly used together with async/await.
assert_rejects.js
var assert = require('assert');
// Async function under test
var fetchFighterData = function(id) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
var db = {
1: { name: 'Yagami Iori', power: 9500 },
2: { name: 'Kusanagi Kyo', power: 9200 },
3: { name: 'Terry Bogard', power: 8800 },
};
if (db[id]) {
resolve(db[id]);
} else {
reject(new Error('Fighter with ID ' + id + ' not found'));
}
}, 10);
});
};
// Use async/await with assert.rejects
(async function() {
// Verify that the promise is rejected
await assert.rejects(
fetchFighterData(99),
{ message: /not found/ }
);
// Verify that the promise is not rejected
await assert.doesNotReject(fetchFighterData(1));
// Verify the resolved value
var fighter = await fetchFighterData(2);
assert.strictEqual(fighter.name, 'Kusanagi Kyo');
assert.strictEqual(fighter.power, 9200);
console.log('rejects tests: all passed');
})();
node assert_rejects.js rejects tests: all passed
Strict Mode — Using assert/strict
Using require('assert/strict') makes loose comparison methods such as assert.equal() and assert.deepEqual() automatically behave as their strict equivalents (using ===). This is the approach used in newer code.
assert_strict_mode.js
// Use assert/strict so all methods are automatically in strict mode
var assert = require('assert/strict');
var getScore = function(name) {
var scores = { 'Yagami Iori': '100', 'Kusanagi Kyo': 95 };
return scores[name];
};
// strictEqual compares with === (fails if types differ)
assert.strictEqual(getScore('Kusanagi Kyo'), 95); // number === number → passes
// '100' (string) and 100 (number) do not match in strict mode
assert.throws(function() {
assert.strictEqual(getScore('Yagami Iori'), 100); // '100' !== 100 → fails
}, assert.AssertionError);
// In assert/strict, equal behaves the same as strictEqual
assert.throws(function() {
assert.equal(getScore('Yagami Iori'), 100); // loose equal also becomes strict
}, assert.AssertionError);
console.log('Strict mode tests: all passed');
node assert_strict_mode.js Strict mode tests: all passed
Overview
The assert module is Node.js's built-in test verification utility. It is often used together with test frameworks such as Jest or Mocha, but it can also be used on its own for simple unit tests.
Use assert.ok(), assert.strictEqual(), and assert.deepStrictEqual() depending on what you need to compare. Use strictEqual for simple primitive values and deepStrictEqual for comparing the contents of objects and arrays. Use assert.throws() for exception verification and assert.rejects() for async rejection.
In newer code, use require('assert/strict') instead of require('assert') so that loose comparison methods like assert.equal() are also unified into strict mode.
Common Mistakes
Common Mistake 1: Confusing assert.equal (loose ==) with assert.strictEqual (=== comparison)
assert.equal() uses == (loose comparison), so values of different types may be considered equal. For example, the number 1 and the string '1' are treated as equal, which can lead to tests passing unintentionally. assert.strictEqual() uses === and detects type differences.
var assert = require('assert');
var getLevel = function(name) {
var data = { 'Itadori Yuji': 1, 'Gojo Satoru': '1' };
return data[name];
};
// Incorrect: assert.equal uses == so 1 == '1' is true
assert.equal(getLevel('Gojo Satoru'), 1); // passes unintentionally (1 == '1')
Correct approach:
var assert = require('assert');
var getLevel = function(name) {
var data = { 'Itadori Yuji': 1, 'Gojo Satoru': '1' };
return data[name];
};
// Correct: strictEqual uses === and detects type differences
assert.strictEqual(getLevel('Itadori Yuji'), 1); // number === number → passes
assert.strictEqual(getLevel('Gojo Satoru'), 1); // '1' !== 1 → AssertionError
Common Mistake 2: Passing a direct call instead of a function reference to assert.throws
The first argument to assert.throws() must be "a function that throws an exception." If you call it directly, the exception occurs before assert.throws() can verify it, or the returned value is not a function, causing an error.
var assert = require('assert');
var exorcise = function(target) {
if (!target) { throw new Error('Target is unknown'); }
return 'Exorcised: ' + target;
};
// Incorrect: calling directly causes the exception before assert.throws can catch it
assert.throws(exorcise(null), Error); // exception happens here, breaking the test
Correct approach:
var assert = require('assert');
var exorcise = function(target) {
if (!target) { throw new Error('Target is unknown'); }
return 'Exorcised: ' + target;
};
// Correct: wrap in a function so assert.throws calls it internally
assert.throws(function() { exorcise(null); }, Error); // passes
Common Mistake 3: Misunderstanding how deepStrictEqual handles key order in objects
assert.deepStrictEqual() considers objects with the same property values equal regardless of key order. For arrays, however, the order of elements is part of the comparison, so a different order will cause a failure.
var assert = require('assert');
var fighter = { name: 'Fushiguro Megumi', grade: 'Grade 1', technique: 'Ten Shadows' };
// Object: deepStrictEqual passes even if key order differs
assert.deepStrictEqual(fighter, {
technique: 'Ten Shadows',
name: 'Fushiguro Megumi',
grade: 'Grade 1',
}); // passes (key order does not matter)
// Array: element order is also compared (different order causes failure)
var names = ['Itadori Yuji', 'Fushiguro Megumi', 'Kugisaki Nobara'];
assert.deepStrictEqual(names, ['Itadori Yuji', 'Fushiguro Megumi', 'Kugisaki Nobara']); // passes
assert.deepStrictEqual(names, ['Fushiguro Megumi', 'Itadori Yuji', 'Kugisaki Nobara']); // fails (different order)
If you find any errors or copyright issues, please contact us.