如何在js-mocha中找到array1包含array2的对象



我有3个数组。我想循环遍历arr1,然后将arr1中的每个对象都包含arr2和arr3的对象与chai断言进行比较。以下是我尝试过的,但失败了

const arr1=[{name="Alice"},{name="Bob"}]
const arr2=[{name="Alice"}]
const arr3=[{name="Bob"}]
for (let i = 0, len = arr1.length; i < len; i++) {
expect(arr1[i]).to.deep.equal(arr2|| arr3);
}

一个简单的方法是将两个数组连接到一个临时数组中,然后继续循环:

const arr4 = [...arr2, ...arr3];
for (let i = 0, len = arr1.length; i < len; i++) {
expect(arr1[i]).to.deep.equal(arr4[i]);
}

这里有一个基于Silviu答案的可能性。使用array.find((函数在arr1中查找与合并数组中的对象匹配的可能匹配项。

如果在其他对象中找到了arr1的所有对象,则测试为绿色,否则测试失败。下面的片段对我来说很容易,但是如果我将{name:"Charlie"}添加到arr1中,我们就会看到它开始失败。

test("Check value in array matches any value in other array", () => {
const arr1=[{name:"Alice"},{name:"Bob"}]
const arr2=[{name:"Alice"}]
const arr3=[{name:"Bob"}]
const merged = [...arr2, ...arr3]
checkValuesExistInChildArray(arr1, merged)
})
const checkValuesExistInChildArray = (arr1, otherArrays) => {
arr1.find(o => {
const match = otherArrays.find(otherObject => otherObject.name === o.name)
expect(match).exist
})
}

最新更新