If you useJest and you need to check that anArray
contains anObject
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:
NOTE:expect.arrayContaining()
must be passed anArray[]
even if you pass one item.
As suggested, if you use this frequently, you might want to create acustom matcher, to avoid the verbose implementation:
code designer, tim.js meetup organizer, speaker, trainer