检查数组是否是另一个数组的子集,并使用js / chai / mocha在断言失败的情况下最后列出所有差异

时间:2018-11-28 17:21:22

标签: javascript mocha chai

考虑 expectedData 子集数组,我想在 actualData array 中进行检查。

我尝试了以下操作,但在出现第一个错误时失败。我希望在执行结束时以断言失败的形式列出实际数组和预期数组之间的所有差异。

expectedData.forEach((item) => {
  assert.deepInclude(actualData, item, 'actual data did not include item')
})

示例数据:

let expectedData = [
  {
      "val": -10.12,
      "key": "ABC"
  },
  {
      "val": 10.12,
      "key": "DEF"
  },
]


let actualData = [
  {
      "val": -10.12,
      "key": "ABC"
  },
  {
      "val": 10.12,
      "key": "DEF"
  },
  {
      "val": 9.8,
      "key": "LMN"
  },
]

2 个答案:

答案 0 :(得分:1)

我不确定为什么初次看时会漏掉这个,但是您发布的代码有一个(很多?)语法错误。试试这个:

let expectedData = [
  {
      "val": -10.1,
      "key": "ABC"
  },
  {
      "val": 10.12,
      "key": "DE"
      },
  {
      "val": 9.8,
      "key": "LMN"
  },
]


let actualData = [
  {
      "val": -10.12,
      "key": "ABC"
  },
  {
      "val": 10.12,
      "key": "DEF"
  },
  {
      "val": 9.8,
      "key": "LMN"
  },
  {
      "val": 1,
      "key": "XYZ"
   },
]

expectedData.forEach((item) => {
  assert.deepInclude(actualData, item, 'actual data did not include item')
})

答案 1 :(得分:0)

找不到任何内置方法。目前,Used For循环迭代每个元素以进行比较并将不匹配项保存到输出数组中。