The Assert module provides a set of assertion functions for verifying invariants. In plain English: it is used for writing tests to verify that your code is behaving exactly as you expect it to.
If an assertion evaluates to false, the module throws an AssertionError and halts the execution of the program.
It is best practice to use the strict mode of the assert module. This ensures that the module uses strictly equal (===) comparisons rather than loose (==) comparisons.
// Import the strict version of assert
const assert = require('assert').strict;
function add(a, b) {
return a + b;
}
// This will pass silently because 2 + 2 is exactly 4
assert.strictEqual(add(2, 2), 4, "Addition function failed!");
try {
// This will throw an error because 2 + 3 is not 6
assert.strictEqual(add(2, 3), 6, "Math broke down!");
} catch (error) {
console.log(error.message); // Outputs: Math broke down!
}
When comparing objects or arrays, strictEqual will fail because they are different references in memory. To test if two objects contain the exact same data, use deepStrictEqual().
const assert = require('assert').strict;
const obj1 = { name: "John", age: 30 };
const obj2 = { name: "John", age: 30 };
// This passes because their properties and values are identical
assert.deepStrictEqual(obj1, obj2);
Which method should you use to verify that two separate arrays contain the exact same elements?