Open In App

What is the role of assert in Node.js ?

Assert is a Node.js module that provides facilitates to writing the test and will not provide any output on the terminal when the test is in the process until any asserting error during the test. It provides various set assertion functions that can be used verifying constants. The assert module in mostly intended for internal use we can use it in the application.

Role of Assert in Node.js: The role of the assert module provides functions for testing expressions. While testing if any of the expressions evaluates to 0 (false) an assertion failure occurs and the program will be terminated.



Advantages of using the Assert module:

Importing module:



const assert = require("assert");

Example 1: The below sample code will not provide any output because the assert case is true.




// Importing assert module
const assert = require('assert');
 
function expression(a, b, c) {
    return (a + b) - c;
}
// Calling the function
const output = expression(1, 2, 1);
assert(output === 2, '(1 + 2) - 1 = 2');

Run the index.js file using the below command:

node index.js

Output

Example 2: The below sample code will display an AssertionError as the assert condition is false.




// Importing the assert module
const assert = require('assert');
 
function expression(a, b, c) {
    return (a + b) - c;
}
// Calling the function
const output = expression(1, 2, 1);
assert(output === 3, '(1 + 2) - 1 = 2');

Run the index.js file using the below command:

node index.js

Output

Article Tags :