16

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?

0

2 Answers 2

13

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')
});
1
  • I actually ended up using the same implementation. I thought that it would be nice to have something built in (like the chai-things implementation above) but actually one forEach cycle is not so bad. Commented Jun 25, 2020 at 16:46
0

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.