Daniel Wolf
Daniel Wolf

Reputation: 13663

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

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?

Upvotes: 15

Views: 15881

Answers (5)

vpmprojects
vpmprojects

Reputation: 3

A variation on the answer by spoonmeiser that uses the copying version of sort, toSorted().

expect(value.toSorted((a, b) => a - b)).toEqual([1, 2, 3])

Upvotes: 0

Jay Wick
Jay Wick

Reputation: 13767

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';

Upvotes: 13

SpoonMeiser
SpoonMeiser

Reputation: 20457

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

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

Upvotes: 4

sesamechicken
sesamechicken

Reputation: 1981

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()));

Upvotes: 0

Andreas Köberle
Andreas Köberle

Reputation: 110972

What about arrayContaining

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

Upvotes: 1

Related Questions