6

I send data to server and match returned data with sent data. If use expect.arrayContaining(array) to compare options and nested variants it swears on ids and fields that add db. How compare objects with arrays which contain arrays of objects ?

Example

Data to send:

{
  "name": "red dress",
  "options": Array [
    Object {
      "name": "size",
      "variants": Array [
        Object {
          "name": "M",
        },
        Object {
          "name": "L",
        },
        Object {
          "name": "S",
        },
      ],
    },
  ],
}

Returned data:

{
  "id": "dc67efd8-dcc4-43df-a8eb-9d95ea641749",
  "name": "red dress",
  "options": Array [
    Object {
      "id": 1,
      "name": "size",
      "productId": "dc67efd8-dcc4-43df-a8eb-9d95ea641749",
      "variants": Array [
        Object {
          "id": 1,
          "name": "M",
          "optionId": 1,
        },
        Object {
          "id": 5,
          "name": "S",
          "optionId": 1,
        },
        Object {
          "id": 6,
          "name": "L",
          "optionId": 1,
        },
      ],
    },
  ],
}

Test:

expect(body.data).toMatchObject(productData)

enter image description here

1
  • The answer below was not what I was looking for. This however did the trick perfectly and gives two solutions: what you need in the Jest expect, and how to extend Jest if you need this functionality in multiple tests medium.com/@andrei.pfeiffer/… Commented Apr 15, 2020 at 16:00

2 Answers 2

1

Maybe you could use a forEach loop to check the relevant data? I presume from your sent data that what matters is the provided options and variants are included in the response.

it('has provided options', () => {
  sent.options.forEach(o => {
    expect(received.options).toContainEqual(
      expect.objectContaining({ name: o.name })
    )
  })
})

Similarly for the variants:

it('has provided variants', () => {
  sent.options[0].variants.forEach(v => {
    expect(received.options[0].variants).toContainEqual(
      expect.objectContaining(v)
    )
  })
})
Sign up to request clarification or add additional context in comments.

Comments

0

use a map to filter only the key you want to check

something like:

expect(yourResponseObject.options.variants.map(e=>({e.name}))).to.include(["blue","red", ... ]);

https://www.chaijs.com/api/bdd/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.