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 interfaceconst {assert} = require('chai')// The function to check if the value is a functionconst checkIfIsFunction= (val) =>{try{// Use the isFunction() methodassert.isFunction(val)}catch(error){console.log(error.message)}}// Invoke the functioncheckIfIsFunction(console.log); // Test successfulcheckIfIsFunction(setTimeout); // Test successfulcheckIfIsFunction(assert); // Test successfulcheckIfIsFunction([1, 2, 3]);checkIfIsFunction({});checkIfIsFunction(null);checkIfIsFunction(assert.isFunction) // Test successfulcheckIfIsFunction(checkIfIsFunction) // Test successful
Explanation
- Line 2: We require the
chaimodule and itsassertinterface. - Line 5: We create a function that runs the test using the
assert.isFunction()method. It takes the value we want to test. With thetry/catchblock, 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.