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

Overview

A testing library, Chai.js, provides interfaces and methods for testing. The assert interface for instance has the isNotNull() method, which checks if a value is not a null.

Syntax

assert.isNotNull(value)
Syntax for isNotNull() in TypeScript

Parameters

value: This is the value we want to check to see if it is not null.

Return value

If the value is null, then nothing is returned, meaning the test was successful. However, if an error is thrown, then it was not successful.

Example

// import the chai module and assert interface
const {assert} = require('chai')
// function to check if value is not null
const checkIfNotNull= (val) =>{
try{
// use the isNotNull
assert.isNotNull(val)
}catch(error){
console.log(error.message)
}
}
// invoke function
checkIfNotNull(1); // test succeeds
checkIfNotNull(0); // test succeeds
checkIfNotNull(""); // test succeeds
checkIfNotNull("foo"); // test succeeds
checkIfNotNull([]); // test succeeds
checkIfNotNull([1, 2, 3]); // test succeeds
checkIfNotNull({}); // test succeeds
checkIfNotNull(null); // test fails

Explanation

  • Line 2: We require the chai package and its interface assert.
  • Line 5: We create a function checkIfNull() that takes a value and invokes the method assert.isNotNull() on the value. With the try-catch block, we handle any exception thrown if the test fails.
  • Lines 15–22: We invoke the function we created and pass some values to it.