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 interfaceconst {assert} = require('chai')// function to check if value is truthyconst checkIfUndefined= (val) =>{try{// use the isUndefined() methodassert.isUndefined(val)}catch(error){console.log(error.message)}}// invoke functioncheckIfUndefined(undefined) // test succeedscheckIfUndefined(this.name) // test succeedscheckIfUndefined(1);checkIfUndefined(0);checkIfUndefined("");checkIfUndefined("foo");checkIfUndefined([]);checkIfUndefined([1, 2, 3]);checkIfUndefined({});checkIfUndefined(null);checkIfUndefined(console.print) // test succeedscheckIfUndefined({}.foo) // test succeeds
Explanation
- Line 2: We require the
chaimodule together with itsassertinterface. - 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 thetry/catchblock, 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.