I'm using Jest to test my Node application.
Is it possible for me to expect/assert a value to be a Date Object?
expect(typeof result).toEqual(typeof Date())
Was my attempt, but naturally returns [Object]. And so this would pass {} too.
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: