In Node.js, chai.js
or chai
is a module for testing codes. With chai
, we can use the assert
interface method called ok()
. This method checks if a value is truthy.
assert.ok(val)
val
: This is the value we want to check for truthiness.
It returns an error if the test fails. If the test was successful, it returns no error.
// import the chai module and assert interfaceconst {assert} = require('chai')// function to check if value is truthyconst checkIfTruthy= (val) =>{try{// use the ok methodassert.ok(val)}catch(error){console.log(error.message)}}// invoke functioncheckIfTruthy(1);checkIfTruthy(0); // test failedcheckIfTruthy(""); // test failedcheckIfTruthy("foo");checkIfTruthy([]);checkIfTruthy([1, 2, 3]);checkIfTruthy({});checkIfTruthy(null); // test failed
chai
module together with its assert
interface.assert.ok()
method. It will take the value we want to test. We use the try/catch
block to catch any error thrown if the test fails.