'Jest: How to expect two arrays to be disjoint
I need to assert that an array does not contain any of the elements of a second array. In other words, I need to assert that two arrays are disjoint.
I have tried the following two approaches. To be clear, I expect the following tests to fail.
it('expects arrays to be disjoint', () => {
expect(['a', 'b', 'c']).not.toEqual(expect.arrayContaining(['c', 'd']));
});
and
it('expects arrays to be disjoint', () => {
expect(['a', 'b', 'c']).toEqual(expect.not.arrayContaining(['c', 'd']));
});
These tests pass, even though the element 'c'
is common to both arrays.
How can I write this test in such a way that the test will fail if the arrays aren't disjoint?
Below is the best that I've been able to do. Is there a more idiomatic way do to it with Jest?
it('expects arrays to be disjoint', () => {
const intersection = ['a', 'b', 'c'].filter((value) => ['c', 'd'].includes(value));
expect(intersection.length).toBe(0);
});
Solution 1:[1]
Your approach looks fine and idiomatic enough as well as .some()
suggested by @jarmod.
There are no native support for such a check for a reason: ordering matters for array(unlike Set
recently introduced as part of ECMAScript). So we way more often need to respect order than ignore it.
Since both filter + includes
and some
run M*N checks, for really long arrays we may convert them both(with M + N operations) into Set
or Object
(using some property as a key) and then check for intersection by in
or Set.has()
(that would need min(M, N) operations). So it would be O(N) instead of O(N^2). But in real world we typically mock some short data for unit tests, until it's something integration testing, so it could be probably be better for readability to has check with some
since it's shorter, more clear => more readable.
Solution 2:[2]
With the 'jest-extended' package the following would be an even shorter version:
expect(['a', 'b', 'c']).not.toIncludeAnyMembers(['c', 'd']);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | skyboyer |
Solution 2 | David Eichelsdörfer |