JavaScript assertequals Explained [6 Practical Examples]

Overview on Javascripp assertequals

JavaScript assertequals are some of the crucial software development assertion tools. You can import the NodeJS built-in assert module or install it with npm.

// import
const assert = require('assert')

// use
assert.equal(<actual>, <expected>, <test name>)

The assert module has several methods to validate a transaction, the main one being equal(), which takes three parameters:

Advertisement
  • actual is the initial value being compared to the second value.
  • expected is the value compared to the actual value. The assertion test fails if the module does not get the expected value. Otherwise, it prints the predetermined output.
  • test name is the message to accompany a failed test. If there is no error, JavaScript assertequals will not show you the result unless you program it.

Apart from the equal() method, you can use the assert functions like ok(), strictEqual(), or notStrictEqual() to achieve the same effect.

Before practically learning how to use the assert methods, here is what you know about JavaScript assertequals.

 

How JavaScript assertequals work

The JavaScript assertequals module is a higher-level implementation of the double-equals operator== without nesting if/else control flows. Here is what we mean.

 

Comparison operators

You can use the Mathematical equal sign = in three main ways in JavaScript.

Single = equal sign assigns a value to a variable. For example, we can create a variable named twentyThree and assign it a value of 23.

const twentyThree = 23

Double == equal sign loosely compares two variants. A loose comparison compares variants without considering data types.

Advertisement

For example 23 == 23 and 23 == '23' are both true, although we don't expect an integer 23 to be equal to a string '23'.

console.log(23 == 23) // true
console.log(23 == '23') // true

Lose comparison can lead to unexpected output. That is why it would be best to use triple equals ===.

Triple === equal sign compares two variants while considering their data types.

console.log(23 === 23)// true
console.log(23 === '23') // false

JavaScript assertequals Explained [6 Practical Examples]

 

Assertion without JavaScript assertequals

Assume we only want to print a message when a function output is false. We can do that by creating a function that compares two numbers.

First, create two files, test.js and test2.js, and open them side-by-side with respective terminals on the Visual Studio Code editor.

Enter the following code in test.js file,

Advertisement
const compare = (actual, expected, message) => {
    if (actual == expected) return
    else console.log(`${message}: ${actual} is NOT equal to ${expected}!`)
}

compare(23, '23', 'Properly compare two values')

and this code in test2.js file.

const compare = (actual, expected, message) => {
    if (actual == expected) return
    else console.log(`${message}: ${actual} is NOT equal to ${expected}!`)
}

compare(23, 59, 'Properly compare two values')

The compare() function takes three parameters: actual, expected, and message values. We compare the actual and expected values. We stop executing the function if the result is true. Otherwise, we print the message using the console object's log() method.

We compare integer 23 and string 23 in test.js. Since the output of the loose comparison is true, the console does not log the message. On the other hand, the message is logged to the console when we compare 23 and 59, resulting in a false output.

JavaScript assertequals Explained [6 Practical Examples]

How does this comparison relate to the JavaScript assertequals module? Find out in the following sections.

 

Use JavaScript assertequals to catch errors in your program

JavaScript assertequals assert.equal() method checks if two values are equal using the double == equals arithmetic operator. It raises an assertion failure if the two values are not equal and terminates the program.

For example, let's check if integer 23 equals integer 23.

Advertisement

Example-1: Confirm equal variables

const assert = require('assert')

const a = 23
const b = 23

assert.equal(a, b, 'Equal integers')

We import the Nodejs built-in assert module with its equal() method. Next, we store the first 23 in variable a, and the second 23 in variable b. We then confirm that a is equal to b. Otherwise, we catch an AssertionError error whose message is Equal integers.

JavaScript assertequals Explained [6 Practical Examples]

 

Example-2: Confirm arithmetic results

Assume we want to confirm if dividing a number by 2 results in a remainder.

const assert = require('assert')
assert.equal(5 % 2, 1, 'Division by 2 results in a remainder')

javascript assertequals example

We can catch a precise` error by introducing exception handling.

 

Use JavaScript assertequals with try-catch

Example-3: Catch a cleaner error message

Assume we want to read the exact error without digging deep into the bulky error message. We can use try-catch as follows.

const assert = require('assert')

const a = 6 % 2;
const b = 1

try {
    assert.equal(a, b)
} catch (error) {
    console.log(`${error}: Division by 2 results in a remainder`)
}

Output:

AssertionError [ERR_ASSERTION]: 0 == 1: Division by 2 results in a remainder

 

This time around, JavaScript assertequals notify us that the output produced AssertionError when the function realized the actual value (of a = (6 modulus 2)) is 0, while the expected value (of b) is 1. The test message is, "Division by 2 results in a remainder."

Advertisement

Bonus tricks

Now that you know how JavaScript assertequals assert.equal() work, it would be best to understand other functions of the assert module that are often confused with the equal() method.

 

JavaScript assert.equal() vs assert.ok() vs assert.strictEqual() vs assert.notStrictEqual() methods

Example-4: Use the ok() method

The ok() method checks if the given value is truthy. Examples of falsy values in JavaScript are false, , null, undefined NaN, and an empty string "".

const assert = require('assert')
let a = undefined
assert.ok(a,'Input is truthy')

If the value is not truthy, the message property throws an assertionError.

 

Example-5: Use strictEqual method

The strictEqual() method works like assert.equal(); the only difference is that it pays attention to data types.

const assert = require('assert')
const a = 23
const b = '23'
assert.strictEqual(a, b, 'Equal numbers')

We get AssertionError because integer 23 is not equal to string '23'.

Advertisement

 

Example-6: Use notStrictEqual method

notStrictEqual is the opposite of strictEqual(). It compares unequal actual and expected values with their data types.

const assert = require('assert')
const a = 23
const b = '25'
assert.notStrictEqual(a, b, 'Numbers strictly NOT equal')

We don't get an error because neither the integer 25 nor the string '25' equal the integer 23. However, we get an error if we replace b with integer 23

JavaScript assertequals Explained [6 Practical Examples]

 

Key Takeaways

JavaScript assertequals confirm the equality of two values using the == operator. You can strictly check equality using assert.strictEqual() method or its opposite assert.notStrictEqual() method.

Lastly, you can apply the assert.ok() method if you are only interested in confirming truthy values. As explained in this tutorial, it would help to understand the concept of truthiness and loose comparison before using the assert functions.

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X