如何匹配两个数组包含开玩笑中的对象数组

时间:2018-05-04 17:47:38

标签: javascript node.js jestjs

我将数据发送到服务器并将返回的数据与发送的数据进行匹配。如果使用expect.arrayContaining(array)比较选项和嵌套变体,它会在添加db的id和字段上发誓。如何将对象与包含对象数组的数组进行比较?

Example

要发送的数据:

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

返回的数据:

{
  "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,
        },
      ],
    },
  ],
}

测试:

expect(body.data).toMatchObject(productData)

enter image description here

2 个答案:

答案 0 :(得分:0)

也许您可以使用forEach循环来检查相关数据?我从您发送的数据中推测,重要的是响应中包括了所提供的选项和变体。

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

类似地:

it('has provided variants', () => {
  sent.options[0].variants.forEach(v => {
    expect(received.options[0].variants).toContainEqual(
      expect.objectContaining(v)
    )
  })
})

答案 1 :(得分:0)

使用map仅过滤您要检查的密钥

类似:

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

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