I needed to write tests for object array but I spent time on how to write it. I write down how to do it to save my time for the next time.
The version of chai is 4.3.4.
Object comparison
For the object comparison, I often use deep.equal
. Normal equal does not work here because the instance is different. If the order is also important, include
can be used.
If deep.equal
is used for the comparison, we can compare the values without thinking about the order. It just compares the values.
There are other ways to compare two objects but this is what I often use.
expect({ a: 1, b: 2 }).to.not.equal({ b: 2, a: 1 });
expect({ a: 1, b: 2 }).to.include({ a: 1, b: 2 });
expect({ a: 1, b: 2 }).to.deep.equal({ a: 1, b: 2 });
expect({ a: 1, b: 2 }).to.deep.equal({ b: 2, a: 1 });
Array comparison
Normal equal does not work either.
expect([1, 2, 3]).to.not.equal([1, 2, 3]);
expect([1, 2, 3]).to.not.equal([3, 2, 1]);
deep.equal
can be used for array comparison as well but it checks the order.
expect([1, 2, 3]).to.deep.equal([1, 2, 3]);
expect([1, 2, 3]).to.not.deep.equal([3, 2, 1]);
If the order can be different, members
function can be used. However, it can’t be used if we want to check if the value contains some values.
expect([1, 2, 3]).to.members([1, 2, 3]);
expect([1, 2, 3]).to.members([3, 2, 1]);
expect([1, 2, 3]).to.not.members([3, 2]);
In this case, include can be used.
expect([1, 2, 3]).to.include(2);
expect([1, 2, 3]).to.include(2).and.include(3);
expect([1, 2, 3]).to.be.an("array").that.includes(2);
But it can be a long statement if there are many values in the array. How can we make it better? Use both include
and members
.
expect([1, 2, 3]).to.include.members([3, 1]);
Object array comparison
This is the main target of this article. It’s an array but the value is objects. Normal equal
cannot be used. deep.equal
can be used only if the order and the values are the same. We need to look for another way if the order can be different.
expect([{ a: 1, b: 1 }, { a: 2, b: 2 }]).to.not.equal([{ a: 2, b: 2 }, { a: 1, b: 1 }]);
expect([{ a: 1, b: 1 }, { a: 2, b: 2 }]).to.deep.equal([{ a: 1, b: 1 }, { a: 2, b: 2 }]);
expect([{ a: 1, b: 1 }, { a: 2, b: 2 }]).to.not.deep.equal([{ a: 2, b: 2 }, { a: 1, b: 1 }]);
The solution is the combination of include
and members
again. The comparison becomes green even if the order of the array and the values in an object are different.
expect([{ a: 1, b: 1 }, { a: 2, b: 2 }]).to.include.deep.members([{ a: 1, b: 1 }, { a: 2, b: 2 }]);
expect([{ a: 1, b: 1 }, { a: 2, b: 2 }]).to.include.deep.members([{ a: 2, b: 2 }, { a: 1, b: 1 }]);
expect([{ a: 1, b: 1 }, { a: 2, b: 2 }]).to.include.deep.members([{ b: 2, a: 2 }, { b: 1, a: 1 }]);
Comments