Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

chaijs
javascript

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

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
Checking if a value is a function using assert.isFunction()

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.

RELATED TAGS

chaijs
javascript

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring