What is the assert.isFunction() method in Chai?

Overview

We can check if a value is a function in Chai using the assert.isFunction() method from the chai library. This method throws an error if the value passed to it is not a function. If the value is a function, nothing happens.

Syntax

Let's view the syntax of the method.

assert.isFunction(value)
Syntax for the assert.isFunction() method in Chai

Parameters

value: We want to test if this value is a function.

Return value

This method throws an error if the test fails. It returns nothing if the test is successful.

Example

Let's view a code example.

// Import the chai module and assert the interface
const {assert} = require('chai')
// The function to check if the value is a function
const checkIfIsFunction= (val) =>{
try{
// Use the isFunction() method
assert.isFunction(val)
}catch(error){
console.log(error.message)
}
}
// Invoke the function
checkIfIsFunction(console.log); // Test successful
checkIfIsFunction(setTimeout); // Test successful
checkIfIsFunction(assert); // Test successful
checkIfIsFunction([1, 2, 3]);
checkIfIsFunction({});
checkIfIsFunction(null);
checkIfIsFunction(assert.isFunction) // Test successful
checkIfIsFunction(checkIfIsFunction) // Test successful

Explanation

  • Line 2: We require the chai module and its assert interface.
  • Line 5: We create a function that runs the test using the assert.isFunction() method. It takes the value we want to test. With the try/catch block, we will catch any error thrown if the test fails.
  • Lines 15–22: We invoke the function we created and test many values of many types.

Free Resources