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 interfaceconst {assert} = require('chai')// function to check if value is not nullconst checkIfNotNull= (val) =>{try{// use the isNotNullassert.isNotNull(val)}catch(error){console.log(error.message)}}// invoke functioncheckIfNotNull(1); // test succeedscheckIfNotNull(0); // test succeedscheckIfNotNull(""); // test succeedscheckIfNotNull("foo"); // test succeedscheckIfNotNull([]); // test succeedscheckIfNotNull([1, 2, 3]); // test succeedscheckIfNotNull({}); // test succeedscheckIfNotNull(null); // test fails
Explanation
- Line 2: We require the
chaipackage and its interfaceassert. - Line 5: We create a function
checkIfNull()that takes a value and invokes the methodassert.isNotNull()on the value. With thetry-catchblock, we handle any exception thrown if the test fails. - Lines 15–22: We invoke the function we created and pass some values to it.