Skip to content

Enhance toHaveProperty() to allow array selection #7284

@stephen-last

Description

@stephen-last

🚀 Feature Proposal

Enhance the .toHaveProperty() matcher to allow array selection, similar to lodash/get.

Motivation

Will allow very easy assertions on very complex objects which contain nested arrays/objects.

Example

const stateData = {
  attributes: {
    all: [
      {
        name: `Colour`,
        values: [
          { name: `Black`, products: [2, 3] },
          { name: `Orange` },
          { name: `Green` },
          { name: `Purple` }
        ]
      }
    ]
  }
}

expect(stateData).toHaveProperty(`attributes.all[0].values[0].products`, [2, 3])
expect(stateData).toHaveProperty(`attributes.all[0].values[2].name`, `Green`)

Pitch

It's an enhancement to an existing matcher which would allow smaller and cleaner tests when asserting against large and complex objects which contain arrays.

As an enhancement, it wouldn't break any existing functionality.

Would bring the path spec in line with the very popular lodash library.

Would meet many peoples expectations of Jest, as I assumed this is a common task and would already be available.

Notes

If I've missed something and asserting deep properties in objects containing arrays is already easy, then sorry, I'm happy to be pointed in the right direction.

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