What is the assert.equal() method in Chai.js?

Overview

We can use Chai.js module for testing our JavaScript applications. The assert is an interface of this module. We can use the equal() method to check if a particular value is equal to another value.

Note: The equal() method is similar to double equality (==).

Syntax

assert.equal(val1, val2)
Syntax for assert.typeOf() in Chai.js

Parameters

  • val1: This is the first value we want to check.
  • val2: This is the second value to check the equality with the first value.

Return value

Nothing is returned if the values are equal. But an error is thrown if val1 and val2 are not equal.

Code

// import the chai module and assert interface
const {assert} = require('chai')
// function to check if values are equal
const checkIfEqual= (val1, val2) =>{
try{
// use the equal() method
assert.equal(val1, val2)
}catch(error){
console.log(error.message)
}
}
checkIfEqual(true, true)
checkIfEqual(false, true) // test failed
checkIfEqual([], {}) // test failed
checkIfEqual(100, "100")
checkIfEqual(null, "null") // test failed
checkIfEqual(null, null)
checkIfEqual(undefined, undefined)

Explanation

  • Line 2: We require the chai module together with its assert interface.
  • Line 5: We create a function that will run the test using the assert.equal() method. It will take the two values we want to check for their equality. With the try/catch block, we will catch any error thrown if the test fails.
  • Lines 14–20: We invoke the function created and test many values.

Free Resources