Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chai.js compare arrays without considering order

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).

like image 811
Balázs Édes Avatar asked Jun 07 '16 19:06

Balázs Édes


3 Answers

You can use the built in check 'members':

expect([4, 2]).to.have.members([2, 4])

like image 91
Delapouite Avatar answered Oct 29 '22 21:10

Delapouite


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/

like image 15

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);
    });
});
like image 3
peteb Avatar answered Oct 29 '22 20:10

peteb