I'm using chai to write unit tests and I would like to assert that two arrays are disjoint (i.e. they do not share any common element).
Something like this:
assert.areDisjoint([1, 2, 3], [2, 4]); // fail
assert.areDisjoint([0], [1, 1, 2]); // pass
assert.areDisjoint(['foo'], ['foo']); // fail
assert.areDisjoint(['foo', 'foo'], []); // pass
I had a look at the many various predefined assertion here and here, but nothing seems to fit.
My current (working) approach:
assert.equal(
new Set([...array1, ...array2]).size,
new Set(array1).size + new Set(array2).size,
'expected iterables to be disjoint'
);
I think you can see why I don't like this method: it makes the intent unclear and bloats the code. I wonder if there is a more elegant way to write this assertion.
A fallback possibility is to create a helper function/method as part of the test code. Then, the tests would look like:
Within the test code the intent is clear, the implementation of the 'areDisjoint' function is at one place and does not cause any code bloat. Unfortunately, in case of a failing test the diagnostic message is not overly helpful, but can only tell something like 'expected true got false' or the like.