The assert
module is one of the core libraries in Node.js, meaning it comes bundled with Node.js installation, and thus, doesn’t require any additional packages to be installed. It provides a straightforward way to write tests for your Node.js applications by performing checks on your code and throwing AssertionError
if the test condition evaluates to false
.
Key methods in Assert module:
- assert(value[, message]): Tests if the value is truthy, it throws an
AssertionError
if the value evaluates asfalse
. - assert.deepEqual(actual, expected[, message]): Tests for deep equality between the actual and expected parameters. It does not compare data types.
- assert.deepStrictEqual(actual, expected[, message]): Tests for deep equality, as
deepEqual
, but considers primitives and their object wrappers to be different, and it checks object prototypes as well. - assert.strictEqual(actual, expected[, message]): Tests strict equality between actual and expected, as determined by the strict equality operator (===).
- assert.rejects(asyncFn[, error][, message]): Awaits the
asyncFn
promise to complete and throws anAssertionError
if the promise is resolved instead of rejected. - assert.doesNotReject(asyncFn[, error][, message]): Awaits the
asyncFn
promise to complete and throws anAssertionError
if the promise is rejected.
These methods throw an AssertionError
when the expected condition is not met, halting the Node.js process.
Example: Using Assert module for testing
The following example demonstrates the usage of some methods in the assert
module. It can be run in any Node.js environment, including online compilers that support Node.js.
const assert = require('assert');
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
async function fetchData() {
return Promise.reject(new Error("Network Error!"));
}
// Example for assert.strictEqual
assert.strictEqual(add(2, 3), 5, 'add(2, 3) should return 5');
// Example for assert.deepStrictEqual
assert.deepStrictEqual(multiply(2, 3), 6, 'multiply(2, 3) should return 6');
// Example for assert.rejects
(async function() {
await assert.rejects(
fetchData(),
new Error("Network Error!"),
'fetchData() should reject with "Network Error!"'
);
console.log('All tests passed!');
})().catch(error => console.error('Test failed:', error.message));
In this script:
We define three functions: add
, multiply
, and an asynchronous fetchData
that returns a rejected promise.
We then perform an equality check on the add
function to ensure it returns the right sum.
A deep equality check is performed on the multiply
function.
Lastly, we check that the fetchData
function indeed returns a promise that gets rejected with the expected error message.
If any of these conditions aren’t met, an error will be logged to the console. Otherwise, “All tests passed!” will be printed.
Get more articles on Java Script
Read more on Shell and Linux related articles
Refer more on python here : Python