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
ES Module
✅ Popular Assert Methods
1. assert.ok(value[, message])
Checks if the value is truthy.
2. assert.equal(actual, expected[, message])
Checks loose equality (==).
3. assert.strictEqual(actual, expected[, message])
Checks strict equality (===).
4. assert.notStrictEqual(actual, expected[, message])
5. assert.deepStrictEqual(actual, expected)
Checks if objects or arrays are equal (structure + values).
6. assert.throws(fn[, error])
Checks if a function throws an error.
7. assert.doesNotThrow(fn[, error])
Checks that a function does not throw.
8. assert.fail([message])
Manually throws an assertion error.
🧪 Example: Basic Test
🏁 Summary Table
| Method | Description |
|---|---|
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 |
