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.
assert.isNotNull(value)
value
: This is the value we want to check to see if it is not null.
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.
// 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
chai
package and its interface assert
.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.