Expect an Array to Contain an Object in Jest

To test if an object appears within an array, the natural first thought is to use toContain as below:

describe('contains test', () => {
  it('should return true', () => {
    const arr = [ { a: 1 }, { b: 2 }, { c: 3 } ]
    expect(arr).toContain( // This will fail.
      { b: 2 }
    )
  })
})

This will actually result in a failure. The matcher is comparing two different instances of the object {b: 2} and expecting two references to the exact same object in memory. Jest will even offer a helpful suggestion with the failure:

Looks like you wanted to test for object/array equality 
with the stricter toContain matcher. 
You probably need to use toContainEqual instead

To make this behave as we want, we need to use toContainEqual, which will compare only the values of the objects, and not their references. The following code works:

describe('contains test', () => {
  it('should return true', () => {
    const arr = [ { a: 1 }, { b: 2 }, { c: 3 } ]
    expect(arr).toContainEqual( // Compare values only.
      { b: 2 }
    )
  })
})

This will now succeed as desired.

 

Expect an Object to Contain Another Object

What if we want to test if an object contains { b: 2 } as one of its key-value pairs, i.e. to contain it as a sub-object?

The following will achieve this:

describe('object contains test', () => {
  it('should return true', () => {
    const myObject = { 
      a: 1, 
      b: 2, 
      c: 3 
    }
    expect(myObject).toEqual(expect.objectContaining(
      { b: 2 }
    ))
  })
})

This will succeed. Note that we used toEqual so that only object values are compared instead of identical object references.

 

Leave a Reply

Your email address will not be published. Required fields are marked *