Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 418
Daniel Wolf Avatar asked May 03 '18 09:05

Daniel Wolf


People also ask

How do you match objects in jest?

With Jest's Object partial matching we can do: test('id should match', () => { const obj = { id: '111', productName: 'Jest Handbook', url: 'https://jesthandbook.com' }; expect(obj). toEqual( expect. objectContaining({ id: '111' }) ); });

How do you match an array in jest?

Array partial matching with Jest's arrayContainingtest('should contain important value in array', () => { const array = [ 'ignore', 'important' ]; expect(array). toEqual(expect. arrayContaining(['important'])) }); This test will pass as long as the array contains the string 'important' .

What is deep equality in jest?

this.equals(a, b) ​ This is a deep-equality function that will return true if two objects have the same values (recursively).

What are matchers in jest?

Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect API doc.


2 Answers

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';
like image 88
Jay Wick Avatar answered Sep 22 '22 05:09

Jay Wick


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

expect(value.sort()).toEqual([2, 1, 3].sort())
like image 36
SpoonMeiser Avatar answered Sep 19 '22 05:09

SpoonMeiser