Open In App

What is the role of assert in Node.js ?

Last Updated : 31 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • It helps to minimize the time to debug the code.
  • It can be reused across multiple projects if developed with the intent of keeping it in mind.
  • It improves error detection.
  • It provides better monitoring of the design and helps in easier debugging of test failures.
  • It can be used for both dynamic simulations as well as in formal verification of the design.

Importing module:

const assert = require("assert");

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

Javascript




// 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.

Javascript




// 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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads