12

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?

Daniel Wolf
  • 12,855
  • 13
  • 54
  • 80
  • Possible duplicate of [Is there an Array equality match function that ignores element position in jest.js?](https://stackoverflow.com/q/40135684/1048572) – Bergi Jun 25 '20 at 13:21

4 Answers4

11

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';
Jay Wick
  • 12,325
  • 10
  • 54
  • 78
2

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

expect(value.sort()).toEqual([2, 1, 3].sort())
SpoonMeiser
  • 19,918
  • 8
  • 50
  • 68
0

What about arrayContaining

expect(value).toEqual(expect.arrayContaining([2, 1, 3]));
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • 8
    `arrayContaining` is similar to what I need. However, `arrayContaining` allows `actual` to have additional values that are not in `expected`. I want to make sure that both arrays contain *exactly the same elements*, only potentially in different orders. – Daniel Wolf May 03 '18 at 12:27
  • Then you have write it by yourself. – Andreas Köberle May 03 '18 at 13:01
0

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()));
sesamechicken
  • 1,928
  • 14
  • 19
  • Your second expect tests that value contains its own items. If you're sorting the lists, surely you don't need to also use `arrayContaining`? – SpoonMeiser Jan 15 '20 at 11:11