We may use the assert interface method isObject(), available in the testing Library chai.js or chai, to know if a value is an object or not.
Let's view the syntax of the method given below:
assert.isObject(value)
value: This is the value we want to test to see if it is an Object or not.
If the test fails, then an error is thrown. The test is successful if nothing is returned.
// import the chai module and assert interfaceconst {assert} = require('chai')// function to check if value is an objectconst checkIfObject= (val) =>{try{// use the isObject() methodassert.isObject(val)}catch(error){console.log(error.message)}}// invoke the functioncheckIfObject({}) // test succeedscheckIfObject([1, 2, 3, 4])checkIfObject(console)checkIfObject(assert.isObject)checkIfObject({language: "JavaScript"}) // test succeedscheckIfObject(new Date())checkIfObject(new Map([["year", 2022]]))checkIfObject(module) // test succeedscheckIfObject(exports) // test succeeds
require() function to import the chai package and its interface assert.checkIfObject() that takes a value and invokes the method assert.isObject() on the value. With the try-catch block, we'll handle any exception thrown if the test fails.