Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for object properties match for an object using Jest?

I have the following code, that when called it returned an object. I want to write a test case that checks if the object has the tree property named accordingly and their value is number, array and bool.

Could you please provide an example using the Jest library?

const location = () => {
  return {
    locationId: 5128581, // nyc usa
    geo: [-74.006, 40.7143],
    isFetching: false
  }
}

export default location
like image 587
Radex Avatar asked Sep 07 '17 19:09

Radex


People also ask

How do you test an object Jest?

To test for object keys and values with Jest, we can use the toMatchObject method. to check if the expected.name property matches the actual.name property. The type property is ignored in the test since type isn't in actual .

What is a matcher in Jest?

Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect API doc.

What's the difference between the toBe and toEqual matchers in Jest?

. toBe compares primitive values or checks referential identity of object instances while toEqual looks for deep equailty.


1 Answers

Try to use expect.objectContaining() and expect.any() to check each property type.

    import location from './whatever'
    describe('location', () => {
      it('should return location object', () => {
        expect(location()).toEqual(expect.objectContaining({
          locationId: expect.any(Number),
          geo: expect.any(Array),
          isFetching: expect.any(Boolean)
        }))
      })
    })
like image 118
GibboK Avatar answered Oct 22 '22 10:10

GibboK