So im running into an issue where I have a response that contains an array of objects, the array isn’t always in the same order based off the response, but I need to verify that at least 1 of the objects in the array of objects contains a specific value (or key/value pair).
IE: pretend the json looks like this:
{
data: [
{
foo: 'Name 1',
bar: '2022-06-07T00:00:00',
},
{
foo: 'Name 2',
bar: '2022-06-07T00:00:00',
},
{
foo: 'Name 3',
bar: '2022-06-07T00:00:00',
}
}
so I would so something like expect(responseBody.data).toContainEqual({foo: "Name 2"})
but that doesn’t work. Would something like toHaveProperty
work better? (Still not sure I understand the difference between toEqual
, toBe
and toContainEqual
etc… are they feel very similar.
edit: I suppose I need to add something, the object itself im checking may contain random data (like dates/timestamps/etc..) so I won’t know specifically ALL the exact data of the object.
2
Answers
The above code checks whether any object in the array contains a specific value of "foo" key, using
some
method.Previous code that I wrote in JS:
The most direct approach is to create an array of strings for the
foo
key, then use the.toContain()
matcher to see if"Name 2"
is in the array.You can also write your own matcher but this may be overkill for this use case, especially if you don’t need a web-first assertion.