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?
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')
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With