Reputation: 64226
I am using the should.js library for assertions in my unit tests and was wondering how I would go about asserting that the contents of a Set
matches the expectation.
let actualValues = new Set();
actualValues.add(2);
actualValues.add(4);
actualValues.add(6);
actualValues.should.be....... ?
My first instinct was to use Array.from(actualValues)
and then compare that with the expected values; but naturally the ordering of actualValues
is undefined since it's a Set
.
The following works; but it seems quite verbose:
actualValues.size.should.be.eql(3);
actualValues.has(2).should.be.true();
actualValues.has(4).should.be.true();
actualValues.has(6).should.be.true();
Upvotes: 0
Views: 1475
Reputation: 146104
You could iterate over one set and assert each item is also in the second set, then assert their sizes are equal.
const should = require('should')
const set1 = new Set(['red', 'green', 'blue']);
const set2 = new Set(['blue', 'red', 'green']);
for (let x of set1) {
set2.has(x).should.be.true()
}
set2.size.should.equal(set1.size)
This might be a good candidate for at least a helper function like haveSameContent(set1, set2)
which you may also be able to code into a should.js
extension if you want to be able to do something like set1.should.have.same.items.as(set2)
.
Upvotes: 1