Friday 2 June 2017

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

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?



via Mankind1023

No comments:

Post a Comment