assert.equal() function in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

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

Live Demo

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

Live Demo

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

Published on 20-May-2021 11:26:14