Jest matching objects in array
Aug 25, 2017 · 1 min read
If you use Jest and you need to check that an Array contains an Object that matches a given structure, .toContain() won’t help you. So, a different approach is required.
Consider the following scenario. You have an array of objects:
const state = [
{ type: 'START', data: 'foo' },
{ type: 'START', data: 'baz' },
{ type: 'END', data: 'foo' },
]… and you want to test that it contains an item like this { type: 'END' } .
You could write the following test:
expect(state).toEqual( // 1
expect.arrayContaining([ // 2
expect.objectContaining({ // 3
type: 'END' // 4
})
])
)The above reads as:
- you expect that your Array equals
- an Array that contains
- an Object that contains
- the following properties
NOTE: expect.arrayContaining() must be passed an Array[] even if you pass one item.
Adding it as a custom matcher
As Martin Hochel suggested, if you use this frequently, you might want to create a custom matcher, to avoid the verbose implementation:
