adamsfamily
adamsfamily

Reputation: 1974

Jest - How to assert that all items in an array are objects and contain certain properties?

I'd like to assert in jest that an array contains objects with certain properties, such as:

[
  { id: 1, name: 'A' },
  { id: 2, name: 'B' },
  { id: 3 }                 // should throw assertion error
]

In chai and chai-things I would do it with should.all.have and it's pretty self descriptive:

result.should.all.have.property('id');
result.should.all.have.property('name');

Is there a similar way to achieve this in jest?

Upvotes: 16

Views: 14091

Answers (2)

Vitor Araujo
Vitor Araujo

Reputation: 122

Use the jest-extended:

const elements = [
 { id: 1, name: 'A' },
 { id: 2, name: 'B' }
]
expect(elements[0]).toContainAllKeys(['id', 'name']);

https://github.com/jest-community/jest-extended#tocontainallkeyskeys

Upvotes: 0

Arnaud Claudel
Arnaud Claudel

Reputation: 3138

You can use toHaveProperty from Jest.

Here's the doc https://jestjs.io/docs/en/expect#tohavepropertykeypath-value

const elements = [
  { id: 1, name: 'A' },
  { id: 2, name: 'B' },
  { id: 3 }                 // should throw assertion error
]

elements.forEach(element => {
    expect(element).toHaveProperty('id')
    expect(element).toHaveProperty('name')
});

Upvotes: 13

Related Questions