What is the assert.isUndefined() method in Chai?

Overview

The isUndefined() method of the testing library chai is used to check if a particular value is undefined. It belongs to the assert interface. If an error is thrown during the test, the test fails, and the value is defined. If nothing happens, then the test was successful and the value is undefined.

Syntax

assert.isUndefined(val)
The assert.isUndefined() method in Chai

Parameters

val: This is the value that we want to check.

Return value

A test error is thrown if the value is defined. However, if nothing happens, the value is undefined, the test is successful, and no error message is displayed on the console.

Example

// import the chai module and assert interface
const {assert} = require('chai')
// function to check if value is truthy
const checkIfUndefined= (val) =>{
try{
// use the isUndefined() method
assert.isUndefined(val)
}catch(error){
console.log(error.message)
}
}
// invoke function
checkIfUndefined(undefined) // test succeeds
checkIfUndefined(this.name) // test succeeds
checkIfUndefined(1);
checkIfUndefined(0);
checkIfUndefined("");
checkIfUndefined("foo");
checkIfUndefined([]);
checkIfUndefined([1, 2, 3]);
checkIfUndefined({});
checkIfUndefined(null);
checkIfUndefined(console.print) // test succeeds
checkIfUndefined({}.foo) // test succeeds

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.isUndefined() method. It will take the value we want to test. With the try/catch block, we'll catch any error thrown if the test fails.
  • Lines 15–22: We invoke the function created and test a set of values to see the results.

Free Resources