How to assert data type with Jest

Viewed 56873

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!

3 Answers

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:

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 are dealing with JSX you can do the following

expect(result.type).toBe(MyComponent);

Example:

component = shallow(<MyWidget {...prop} />);

instance = component.instance();
const result = instance.myMethod();

expect(result.type).toBe(MyComponent);

In this example myMethod() return MyComponent and we are testing for it.

Related