Jest: Array.toContain() with expect.objectContaining

Created on 1 Jul 2017  路  7Comments  路  Source: facebook/jest

What is the current behavior?
It seems that .toContain() can't be combined with expect.objectContaining. There might be another solution to test if an array of objects contains a specific object, but I somehow thought that combining toContain with expect.objectContaining would do the trick.

Example Test

  test('Array with Object Containing', () => {
    expect(
      [
        { a: 1, b: 2 }, 
        { c: 1, d: 1 }
      ])
      .toContain(
        expect.objectContaining({ a: 1, b: expect.anything() })
      )
  })

Output

 Array with Object Containing

    expect(array).toContain(value)

    Expected array:
      [{"a": 1, "b": 2}, {"c": 1, "d": 1}]
    To contain value:
      ObjectContaining {"a": 1, "b": Anything}

Most helpful comment

@KeKs0r If this helps!

test('Array with Object Containing', () => {
  expect(
    [
      { a: 1, b: 2 }, 
      { c: 1, d: 1 }
    ])
    .toContainEqual(
      expect.objectContaining({ a: 1, b: expect.anything() })
    )
})

Is passing without any issues.

All 7 comments

FWIW, check out #2143

@KarandikarMihir
I think I am missing something. How can I use Object.keys to find a specific object in my array of objects?

@KeKs0r If this helps!

test('Array with Object Containing', () => {
  expect(
    [
      { a: 1, b: 2 }, 
      { c: 1, d: 1 }
    ])
    .toContainEqual(
      expect.objectContaining({ a: 1, b: expect.anything() })
    )
})

Is passing without any issues.

@anilreddykatta thanks this is working fine..

I just ran into the same issue. I find it a little confusing that toContain uses strict equality checks, whereas toContainEqual does not. Their names would imply the converse is true?

@WickyNilliams I agree that the naming there is a bit confusing, but you have to think like this: toContain asserts that it contains an exact thing, and in the case of objects, if it isn't the exact same object by reference, it fails. toContainEqual means if it looks the same by shape, it's ok. So it kinda makes sense, but it would have been better to reverse it and have a toContainStrict or something like that.

Coming back with more experience of jest, I would say the naming is ok. The toEqual matcher is the equivalent of toContainEqual, in that both test deep equality, not reference equality.

Was this page helpful?
0 / 5 - 0 ratings