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.
assert.isUndefined(val)
val
: This is the value that we want to check.
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.
// 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
chai
module together with its assert
interface.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.