2

I am trying to test two array of objects are exactly equal, tried with toEqual matcher but seems it only works for Array of strings, is there any matcher available in Jest to satisfy the condition. please dont mark this as dulplicate , I didn't find an clear answers.

const arr1 = [{name: 'sam', degree: 'engineer', age: '23'}, {name: 'jane', degree: 'accounts', age: '25'}]
const arr2 = [{name: 'jane', degree: 'accounts', age: '25'},{name: 'sam', degree: 'engineer', age: '23'}]

expect(arr1).toEqual(arr2)  // should pass the testcase
muthu
  • 723
  • 10
  • 27
  • 1
    `toEqual` works fine on arrays of objects as well, but not on arrays whose elements are in the wrong order. – Bergi Oct 31 '20 at 04:48

2 Answers2

1

You can resolve it as a series of expectations.

expect(arr1).toBeArray();
expect(arr2).toBeArray();
expect(arr1).toBeArrayOfSize(arr2.length);
expect(arr2).toBeArrayOfSize(arr1.length);

next loop each array and check if the second contains its element

arr1.forEach(item => {
   expect(arr2).toContain(item);
});

and

arr2.forEach(item => {
   expect(arr1).toContain(item);
});
bensiu
  • 24,660
  • 56
  • 77
  • 117
1

This works for me

            const sortResponseData = arr1.sort((a: any, b: any) => {
              return a.name > b.name
                ? 1
                : b.name > a.name
                ? -1
                : 0;
            });
            const sortEntityMetaData = arr2.sort((a: any, b: any) => {
              return a.name > b.name
                ? 1
                : b.name > a.name
                ? -1
                : 0;
            });
            expect(sortResponseData).toEqual(sortEntityMetaData);

muthu
  • 723
  • 10
  • 27