Movatterモバイル変換


[0]ホーム

URL:


Sitemap
Open in app

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:

  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 anArray[] even if you pass one item.

Adding it as a custom matcher

As

suggested, if you use this frequently, you might want to create acustom matcher, to avoid the verbose implementation:

--

--

Andrei Pfeiffer
Andrei Pfeiffer

Written by Andrei Pfeiffer

code designer, tim.js meetup organizer, speaker, trainer

Responses (10)


[8]ページ先頭

©2009-2025 Movatter.jp