Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert data type with Jest

Tags:

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!

like image 928
Jack.c Avatar asked Jun 24 '20 22:06

Jack.c


People also ask

What is assert in Jest?

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.

How do you match objects in Jest?

To match part of an Array in Jest, we can use expect. objectContaining(partialObject) .

Which assertion used to test a value is with exact equality in Jest?

Jest documentation reads: toBe just checks that a value is what you expect. It uses === to check strict equality.

Is object a Jest?

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' .


2 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 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:

  • 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
like image 61
Laode Muhammad Al Fatih Avatar answered Sep 19 '22 17:09

Laode Muhammad Al Fatih


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 
like image 22
Plausibly Deniable Avatar answered Sep 17 '22 17:09

Plausibly Deniable