Skip to content

objectContaining should be recursive but isn't #10462

Closed as not planned
Closed as not planned
@BuckAMayzing

Description

@BuckAMayzing

🐛 Bug Report

I couldn't find a duplicate of this, even though it seems like something that could have come up before. The closest I found was #10186, which is related, but only tangentially.

expect.objectContaining does not work recursively as docs state.

To Reproduce

Here's a small test that will fail:

it('testy test test', () => {
  const expected = {
    a: 1,
    subProps: {
      someArray: [1],
    },
  }

  const received = {
    a: 1,
    subProps: {
      someArray: [1],
      someOtherArray: [],
    },
  }

  expect(received).toEqual(expect.objectContaining(expected))
})

Expected behavior

The test above should have passed according to the docs.

Link to repl or repo (highly encouraged)

Passing and failing tests here

envinfo

doesn't appear to be environment specific - repl and local machines both reproduce. I can add mine and repl's if it seems to be necessary.

workaround

use toMatchObject instead (which incidentally seems to have a nicer api)

additional info

If we look at toMatchObject vs objectContaining, the customTesters passed to the equals function differ - it looks like toMatchObject is actually true subset equality where objectContaining is only subset equality for the first level in the object - in this loop, recursion isn't happening.

Looks like there are two options to fix this: either objectContaining can implement a recursive asymmetricMatch, or it can share a code path with toMatchObject, since the two appear to be trying to accomplish the same goal (unless I'm missing something). The latter seems easier, at least on the surface, but I've not looked into it deeply.

It also looks like #10430 could potentially replace this fix, and objectContaining could become deprecated in favor of toMatchObject.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions