for Jest with newer version > 16.0.0:
There is a new matcher called toBeInstanceOf. You can use the matcher to compare instances of a value.
Example:
expect(result).toBeInstanceOf(Date)
for Jest with version < 16.0.0:
Use instanceof to prove whether the result variable is a Date Object or Not.
Example:
expect(result instanceof Date).toBe(true)
Another example to match common types:
boolean
expect(typeof target).toBe("boolean")
number
expect(typeof target).toBe("number")
string
expect(typeof target).toBe("string")
array
expect(Array.isArray(target)).toBe(true)
object
expect(target && typeof target === 'object').toBe(true)
null
expect(target === null).toBe(true)
undefined
expect(target === undefined).toBe(true)
function
expect(typeof target).toBe('function')
Promise or async function
expect(!!target && typeof target.then === 'function').toBe(true)
Another example to match further types:
float (decimal number. i.e. 3.14, 137.03, etc.)
expect(Number(target) === target && target % 1 !== 0).toBe(true)
Promise or async function that return an Error
await expect(asyncFunction()).rejects.toThrow(errorMessage)
References:
- https://jestjs.io/docs/expect#tobeinstanceofclass
- https://github.com/facebook/jest/issues/3457
- https://futurestud.io/tutorials/detect-if-value-is-a-promise-in-node-js-and-javascript