What I'd like to do is compare 2 arrays of primitives using chai.js, but without considering the order of elements - like if they were 2 sets.
Now obviously I can do something like this:
const actual = ['a', 'b', 'c'];
const expected = ['b', 'c', 'a'];
expect(actual).to.have.length(expected.length);
expected.forEach(e => expect(actual).to.include(e));
But I'm curious if there is a prefered 'built in' way of doing this (I couldn't find it in the docs).
You can use the built in check 'members':
expect([4, 2]).to.have.members([2, 4])
Answers above expect([4, 2]).to.have.members([2, 4])
won't check the size as author mentioned about.
expect([1,2,2]).to.have.members([1,2])
will pass the test.
The best option is to use https://www.chaijs.com/plugins/deep-equal-in-any-order/
You can use the members assertion from chai BDD.
var mocha = require('mocha');
var should = require('chai').should();
let a = ['a', 'b', 'c'];
let b = ['c', 'a', 'b'];
let c = ['d', 'e', 'c', 'b'];
describe('test members', function() {
it('should pass', function() {
a.should.have.members(b);
});
it('should fail', function() {
a.should.not.have.members(c);
});
});
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