The assert module provides a bunch of different functionalities that are used for function assertion. Assert.equal() function is one of them. This function is used to test the equality between the actual and expected parameters. An assertion error will be raised if the condition is not fulfilled.
Syntax
assert.equal(actual, expected[, message])
Parameters
The above parameters are described as below −
actual – This is the actual value that will be evaluated against the expected parameters.
expected – This is the expected parameter value that is matched against the actual value.
message – This parameter holds the string message value to be printed if the actual and expected parameters do not match. It is an optional field.
Installing the Assert Module
npm install assert
The assert module is an inbuilt Node.js module, so you can skip this step as well. You can check the assert version using the following command to get the latest assert module.
npm version assert
Importing the module in your function
const assert = require("assert");
Example
Create a file with the name – assertEqual.js and copy the below code snippet. After creating the file use the below command to run this code.
node assertEqual.js
assertEqual.js
// Importing the module const assert = require('assert').strict; var a = 21; var b = 20; // Function call try { // Checking if both a & b are equal assert.equal(a, b); } catch(error) { console.log("Error: ", error) }
Output
C:\home\node>> node assertEqual.js Error: { AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B: + expected - actual - 21 + 20 at Object.<anonymous> (/home/node/mysql-test/assert.js:10:9) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3) generatedMessage: true, name: 'AssertionError [ERR_ASSERTION]', code: 'ERR_ASSERTION', actual: 21, expected: 20, operator: 'strictEqual' }
We can see in the above example that both the values are not equal.
Example
Let's take a look at one more example.
// Importing the module const assert = require('assert'); var a = 20; var b = '20'; // Function call try { // Checking if both a & b are equal assert.equal(a, b); console.log("a and b are equal") } catch(error) { console.log("Error: ", error) }
Output
C:\home\node>> node assert.js a and b are equal
We can see in the above example that a is an integer value, whereas b is a string value. But the inside contents are equal. Therefore, the output gives us both a and b are equal.