Jest matching objects in array

Andrei Pfeiffer
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:

  1. you expect that your Array equals
  2. an Array that contains
  3. an Object that contains
  4. 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:

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade