Radex
Radex

Reputation: 8587

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

Upvotes: 38

Views: 33099

Answers (1)

GibboK
GibboK

Reputation: 73918

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)
        }))
      })
    })

Upvotes: 82

Related Questions