Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 264
adamsfamily Avatar asked Jan 17 '26 12:01

adamsfamily


1 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')
});
like image 181
Arnaud Claudel Avatar answered Jan 20 '26 22:01

Arnaud Claudel