How do I compare two collections in Jest ignoring element order?

≯℡__Kan透↙ 提交于 2021-01-20 04:15:57

问题


When writing a unit test in Jest, how can I test that an array contains exactly the expected values in any order?

In Chai, I can write:

const value = [1, 2, 3];
expect(value).to.have.members([2, 1, 3]);

What's the equivalent syntax in Jest?


回答1:


Another way is to use the custom matcher .toIncludeSameMembers() from jest-community/jest-extended.

Example given from the README

test('passes when arrays match in a different order', () => {
    expect([1, 2, 3]).toIncludeSameMembers([3, 1, 2]);
    expect([{ foo: 'bar' }, { baz: 'qux' }]).toIncludeSameMembers([{ baz: 'qux' }, { foo: 'bar' }]);
});

It might not make sense to import a library just for one matcher but they have a lot of other useful matchers I've find useful.

Additional note, if you're using Typescript, you should import the types for the methods added to expect with this line:

import 'jest-extended';



回答2:


I would probably just check that the arrays were equal when sorted:

expect(value.sort()).toEqual([2, 1, 3].sort())



回答3:


What about arrayContaining

expect(value).toEqual(expect.arrayContaining([2, 1, 3]));



回答4:


Perhaps you could use the array.sort method to line up the order in conjunction with the arrayContaining method. You might also include a length test for good measure.

const value = [1, 2, 3];
expect(value).toHaveLength(3);
expect(value.sort()).toEqual(expect.arrayContaining(value.sort()));


来源:https://stackoverflow.com/questions/50152112/how-do-i-compare-two-collections-in-jest-ignoring-element-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!