使用 Chai 查看两个对象是否相同,其中一个属性具有不同的顺序

问题描述 投票:0回答:2

我有两个对象数组:

array1 = [ 
  { name: 'Kitty, Hello',
    otherNames: [ '(1) One', '(2) Two' ] 
  },
  { name: 'Cat, Garfield',
    otherNames: [ '(3) Three' ] 
  } 
];

array2 = [ 
  { name: 'Kitty, Hello',
    otherNames: [ '(2) Two', '(1) One' ] 
  },
  { name: 'Cat, Garfield', 
    otherNames: [ '(3) Three' ] 
   } 
]

我正在尝试使用 Chai 来查看它们是否相等,尽管

otherNames
array1
和 `array2 中的顺序不同。

我已经尝试过:

array1.to.be.eql(array2) //false
array1.to.have.deep.members(array2) //false

但它一直返回 false。这可能吗?我尝试过查看类似的问题,但我只能找到“name”和“otherNames”顺序不同的问题。

javascript chai equality
2个回答
1
投票

它们不相等,因为它们在数组中具有不同的值。您可以对数组进行排序并检查它们是否相等。

const getSortedAtKey = (array, key = 'otherNames') => {
  return array.map(value => ({
    ...value,
    [key]: value[key].sort()
  }));
}

expect(getSortedAtKey(array1)).to.eql(getSortedAtKey(array2))

这个函数很好,因为你可以将它链接到多个属性(如果你有例如

otherNames
otherAges
数组,你想验证你可以调用
getSortedAtKey(getSortedAtKey(array1), 'otherAges')


0
投票

有一个包可以做到这一点。 https://www.npmjs.com/package/deep-equal-in-any-order

const deepEqualInAnyOrder = require('deep-equal-in-any-order');
const chai = require('chai');

chai.use(deepEqualInAnyOrder);

const { expect } = chai;

expect(array1).to.deep.equalInAnyOrder(array2);
© www.soinside.com 2019 - 2024. All rights reserved.