Node Mocha / Chai Unit Tests - Compare array of objects regardless of order

Viewed 1728

I'm trying to do some unit tests comparing an array of results to an array it should look like, unfortunately the results come from an api with delays so the order of objects is not always the same, which causes the test to fail:

Simplified example

var a = [
    {name: 'Joe', age: 35},
    {name: 'Steve', age: 30},
]

//assume we got the result in this order
var b = [
    {name: 'Steve', age: 30},
    {name: 'Joe', age: 35},
]

expect(a).to.deep.equal(b) //Fails

My current workaround is to do this:

expect(a.length).to.equal(b.length);
for(let item of b){
    expect(a).to.deep.contain(item);
}

But I'm looking for a way to do a deep comparison directly without regard to order in Mocha / Chai, is it possible?

update: This is a bit of a hack, but it might helps in case anyone needs it, you can put the whole thing in a try / catch and on error use deep contain:

try{
    expect(a).to.have.deep.members(b);
}catch(e){
    expect(a).to.deep.equal(b);
}

If the first test fails, it runs the second which will also fail but prints out the differences.

1 Answers
Related