期望数组相等,忽略顺序

2022-01-11 00:00:00 jasmine javascript karma-jasmine

使用 Jasmine 是否可以测试 2 个数组是否包含相同的元素,但顺序不一定相同?即

With Jasmine is there a way to test if 2 arrays contain the same elements, but are not necessarily in the same order? ie

array1 = [1,2,3];
array2 = [3,2,1];

expect(array1).toEqualIgnoreOrder(array2);//should be true

推荐答案

如果只是整数或者其他原始值,可以sort() 比较之前的它们.

If it's just integers or other primitive values, you can sort() them before comparing.

expect(array1.sort()).toEqual(array2.sort());

如果它的对象,将其与 map() 函数提取将要比较的标识符

If its objects, combine it with the map() function to extract an identifier that will be compared

array1 = [{id:1}, {id:2}, {id:3}];
array2 = [{id:3}, {id:2}, {id:1}];

expect(array1.map(a => a.id).sort()).toEqual(array2.map(a => a.id).sort());

相关文章