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

Viewed 4053

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?

2 Answers

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')
});
Related