What is the assert.ok() method in chai.js?
Overview
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.
Syntax
assert.ok(val)
The syntax for assert.ok() method in chai
Parameters
val: This is the value we want to check for truthiness.
Return value
It returns an error if the test fails. If the test was successful, it returns no error.
Example
// 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
Explanation
- Line 2: We import the
chaimodule together with itsassertinterface. - Line 5: We create a function that runs the test using the
assert.ok()method. It will take the value we want to test. We use thetry/catchblock to catch any error thrown if the test fails. - Lines 15–22: We invoke the function we created and test multiple values with many types.