Is there an Array equality match function that ignores element position in jest.js?
There is no built-in method to compare arrays without comparing the order, but you can simply sort the arrays using .sort()
before making a comparison:
expect(["ping wool", "diorite"].sort()).toEqual(["diorite", "pink wool"].sort());
You can check the example in this fiddle.
Put the elements into a set. Jest knows how to match these.
expect(new Set(["pink wool", "diorite"])).toEqual(new Set(["diorite", "pink wool"]));
As already mentioned expect.arrayContaining
checks if the actual
array contains the expected
array as a subset.
To check for equivalence one may
- either assert that the length of both arrays is the same (but that wouldn't result in a helpful failure message)
- or assert the reverse: That the
expected
array contains theactual
array:
// This is TypeScript, but remove the types and you get JavaScript
const expectArrayEquivalence = <T>(actual: T[], expected: T[]) => {
expect(actual).toEqual(expect.arrayContaining(expected));
expect(expected).toEqual(expect.arrayContaining(actual));
};
This still has the problem that when the test fails in the first assertion one is only made aware of the elements missing from actual
and no the extra ones that are not in expected
.