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 {}.
Thanks!
assertions(number) verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.
To match part of an Array in Jest, we can use expect. objectContaining(partialObject) .
Jest documentation reads: toBe just checks that a value is what you expect. It uses === to check strict equality.
The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via import {jest} from '@jest/globals' .
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 Date
Object or Not.
Example:
expect(result instanceof Date).toBe(true)
Another example to match primitive types:
boolean
, number
, string
& function
:
expect(typeof target).toBe("boolean") expect(typeof target).toBe("number") expect(typeof target).toBe("string") expect(typeof target).toBe('function')
array
& object
:
expect(Array.isArray(target)).toBe(true) expect(target && typeof target === 'object').toBe(true)
null
& undefined
:
expect(target === null).toBe(true) expect(target === undefined).toBe(true)
Promise
or async function
:
expect(!!target && typeof target.then === 'function').toBe(true)
References:
Jest supports toBeInstanceOf
. See their docs, but here is what they have for example at the time of this answer:
class A {} expect(new A()).toBeInstanceOf(A); expect(() => {}).toBeInstanceOf(Function); expect(new A()).toBeInstanceOf(Function); // throws
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With