Categories
JavaScript Answers

How to expect arrays to be equal ignoring order with Jest and JavaScript?

Spread the love

Sometimes, we want to expect arrays to be equal ignoring order with Jest and JavaScript.

In this article, we’ll look at how to expect arrays to be equal ignoring order with Jest and JavaScript.

How to expect arrays to be equal ignoring order with Jest and JavaScript?

To expect arrays to be equal ignoring order with Jest and JavaScript, we can use the toEqual method to compare an array of primitive values.

For instance, we write

expect(array1.sort()).toEqual(array2.sort());

to call sort to sort array1 and array2.

Then we call toEqual with the sorted version of array2 to see if it’s the same as the sorted version of array1.

This works if array1 and array2 only have primitive values.

If they don’t have primitive values, then we’ve to convert them to arrays that have primitive values.

For instance, we write

const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
const array2 = [{ id: 3 }, { id: 2 }, { id: 1 }];

expect(array1.map((a) => a.id).sort()).toEqual(array2.map((a) => a.id).sort());

to call map to map both arrays to arrays with only the id property values.

And then we do the comparisons.

Conclusion

To expect arrays to be equal ignoring order with Jest and JavaScript, we can use the toEqual method to compare an array of primitive values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *