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.
Let's view the syntax of the method.
assert.isFunction(value)
value
: We want to test if this value is a function.
This method throws an error if the test fails. It returns nothing if the test is successful.
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
chai
module and its assert
interface.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.