Node.js Assertion Testing
The Node.js assert module provides a simple way to verify that your code behaves as expected. It checks specific conditions, known as assertions, and throws an error whenever an assertion fails. If the assertion passes, the program continues without producing an error.
Table of Contents
Note: The assert module is useful for quick validations and internal checks, but it is not a complete testing framework. For larger test suites, tools such as Jest or Mocha are more suitable.
Example 1: Passing Assertion
// assert_example1.js
const assert = require('assert');
function add(a, b) {
return a + b;
}
const expected = add(1, 2);
assert(expected === 3, 'one plus two should be three');
// No output - assertion passed
In this example, add(1, 2) returns 3, so the assertion succeeds and the program continues normally.
Complete Advance AI Topics: Click Here
SQL Tutorial: Click Here
Example 2: Failing Assertion
// assert_example2.js
const assert = require('assert');
function add(a, b) {
return a + b;
}
assert(add(1, 2) === 4, 'one plus two should be three');
// AssertionError [ERR_ASSERTION]: one plus two should be three
Here, the function returns 3, but the assertion expects 4. Because the condition is false, Node.js throws an AssertionError.
Common assert Methods
| Method | Description |
|---|---|
assert(value) | Passes when the specified value is truthy. |
assert.strictEqual(a, b) | Checks strict equality using ===. |
assert.deepStrictEqual(obj1, obj2) | Compares objects and arrays deeply. |
assert.throws(fn) | Passes when the specified function throws an error. |
assert.rejects(asyncFn) | Passes when the specified asynchronous function returns a rejected promise. |
Using Strict Mode
Modern Node.js applications can use node:assert/strict for stricter assertion behavior.
const assert = require('node:assert/strict');
assert.equal(1, '1');
// Throws because strict mode requires matching types
Strict mode helps catch unexpected type differences and makes assertions more precise.
Download New Real Time Projects:- Click here
Conclusion
The Node.js assert module is useful for quick validation, debugging, and checking conditions in small scripts. When you need to build complete and organized test suites, testing frameworks such as Jest or Mocha provide additional features and functionality.
Keywords
Node.js Assertion Testing, Node.js assert module, Node.js assert, Node.js testing, Node.js assertions, assert.strictEqual, assert.deepStrictEqual, assert.throws, assert.rejects, Node.js strict mode, Node.js tutorial