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?
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' }) ); });
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' .
this.equals(a, b) This is a deep-equality function that will return true if two objects have the same values (recursively).
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.
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';
I would probably just check that the arrays were equal when sorted:
expect(value.sort()).toEqual([2, 1, 3].sort())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With