Node.js Assert Module

Node.js Assert Module

The Assert module in Node.js provides a set of assertion functions used for writing tests. Assertions check whether a condition is true; if it is not, Node.js throws an error.
It is commonly used in unit testing.

The module is built-in — no installation is needed.


✔️ Importing the Assert Module

CommonJS

const assert = require('assert');

ES Module

import assert from 'node:assert';

Popular Assert Methods


1. assert.ok(value[, message])

Checks if the value is truthy.

assert.ok(true); // Pass
assert.ok(1); // Pass
assert.ok(false); // Fail

2. assert.equal(actual, expected[, message])

Checks loose equality (==).

assert.equal(5, '5'); // Pass
assert.equal(5, 6); // Fail

3. assert.strictEqual(actual, expected[, message])

Checks strict equality (===).

assert.strictEqual(5, 5); // Pass
assert.strictEqual(5, '5'); // Fail

4. assert.notStrictEqual(actual, expected[, message])

assert.notStrictEqual(5, 6); // Pass
assert.notStrictEqual(5, 5); // Fail

5. assert.deepStrictEqual(actual, expected)

Checks if objects or arrays are equal (structure + values).

assert.deepStrictEqual({a:1}, {a:1}); // Pass
assert.deepStrictEqual([1,2], [1,2]); // Pass

6. assert.throws(fn[, error])

Checks if a function throws an error.

assert.throws(() => {
throw new Error("Something went wrong");
});

7. assert.doesNotThrow(fn[, error])

Checks that a function does not throw.

assert.doesNotThrow(() => {
return 10;
});

8. assert.fail([message])

Manually throws an assertion error.

assert.fail("Forced failure");

🧪 Example: Basic Test

const assert = require('assert');

function add(a, b) {
return a + b;
}

assert.strictEqual(add(2, 3), 5);
assert.notStrictEqual(add(2, 2), 5);

console.log("All tests passed!");


🏁 Summary Table

MethodDescription
assert.ok()Checks if value is truthy
assert.equal()Loose equality
assert.strictEqual()Strict equality
assert.deepStrictEqual()Deep comparison
assert.throws()Function must throw error
assert.doesNotThrow()Function must not throw
assert.fail()Force fail

You may also like...