Rayrun
← Back to Discord Forum

Expect array to contain object

I have and array of objects. It looks like array = [{id: 1, name: John}, {id: 2, name: Jane}]. Now I want to assert the array contains "name: Jane".

I tried something like this, but it does not work: expect(array).toContain(expect.objectContaining({ name: "Jane" }))

This thread is trying to answer question "How can I assert if an array of objects contains a specific object in Jest?"

4 replies

Hi, I suggest to use chai assertion library... there you have pretty cool stuff which help you to check the array in different ways.. Have a look here -> https://medium.com/@mati-qa/playwright-chai-thats-all-what-you-need-3628b9293f60 And here is the library -> https://www.chaijs.com/api/bdd/#method_members

You should be able to achieve this in Jest by using the .toEqual() matcher in conjunction with expect.arrayContaining() and expect.objectContaining():

expect(array).toEqual(expect.arrayContaining([expect.objectContaining({ name: "Jane" })]))

dmitry_67935
dmitry_67935

Example from here https://playwright.dev/docs/next/api/class-genericassertions#generic-assertions-to-equal Just try to use expect(array).toEqual(expect.arrayContaining(value))

list: [1, 2, 3],
  obj: { prop: 'Hello world!', another: 'some other value' },
  extra: 'extra',
}).toEqual(expect.objectContaining({
  list: expect.arrayContaining([2, 3]),
  obj: expect.objectContaining({ prop: expect.stringContaining('Hello') }),
}));```

This seems to pass:

const asdf = [{a: 1, b: 2}, {a: 3, b: 4}];
expect(asdf).toEqual(
  expect.arrayContaining(
    [
      expect.objectContaining(
        {a: 1}
      )
    ]
  )
)

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.