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 interface
const {assert} = require('chai')
// function to check if value is truthy
const checkIfTruthy= (val) =>{
try{
// use the ok method
assert.ok(val)
}catch(error){
console.log(error.message)
}
}
// invoke function
checkIfTruthy(1);
checkIfTruthy(0); // test failed
checkIfTruthy(""); // test failed
checkIfTruthy("foo");
checkIfTruthy([]);
checkIfTruthy([1, 2, 3]);
checkIfTruthy({});
checkIfTruthy(null); // test failed

Explanation

  • Line 2: We import the chai module together with its assert interface.
  • 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 the try/catch block 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.