The equal
method of the assert
module in Node.js uses the ==
operator (Abstract Equality Comparison) to check for equality between two values.
The process is illustrated below:
Note: You can view a list of rules for the
==
operator here.
To use the equal
method, you will need to install the assert
module using the command prompt as shown below:
npm install assert
After the installation is complete, you will need to import the assert
module into the program as shown below:
const assert = require('assert');
The prototype of the equal
method is shown below:
equal(actual, expected[, message])
The equal
method takes the following parameters:
actual
: The first of the two values to compare.
expected
: The second of the two values to compare.
message
: This optional parameter holds the error message in case of an AssertionError. If this parameter is left empty, a default message is assigned.
If the values are not equal, then the equal
method throws an AssertionError, and the program terminates; otherwise, execution continues as normal.
In case of an error, the message
property of the AssertionError
is set equal to the message
parameter. If the message
parameter is not provided, a default value is assigned to the message
property of the AssertionError
.
Note: The
equal
method also handlesNaN
(Not-A-Number) comparisons. If both values areNaN
, theequal
method recognizes them as being identical.
The code below shows how the equal
method works in Node.js:
const assert = require('assert');// evaluating first expressiontry{assert.equal(10, 10, "Assertion Error: The values are inequal.")console.log("No error.")}catch(error){console.log(error.message)}// evaluating second expressiontry{assert.equal(10, "10", "Assertion Error: The values are inequal.")console.log("No error.")}catch(error){console.log(error.message)}// evaluating third expressiontry{assert.equal(10, 5, "Assertion Error: The values are inequal.")console.log("No error.")}catch(error){console.log(error.message)}
The code above uses different expressions to show the behavior of the equal
method.
In the first expression in line , the actual
and expected
parameters are both , so the equal
method does not throw any errors. Therefore, only the try
branch of the try-catch
block executes.
In the second expression in line , the actual
and expected
parameters are again , but they have different types. The actual
parameter is an integer, whereas the expected
parameter is a string. Since the equal
method uses abstract equality comparison rules, it considers the two values equal and does not throw any errors. Therefore, only the try
branch of the try-catch
block executes.
In the third expression in line , the actual
and expected
parameters are unequal, so an error is thrown, which triggers the catch
branch of the try-catch
block. The code outputs the message associated with the error, i.e., the string provided as the message
parameter to the equal
method in line .
Free Resources