While working on a unit test case created with mocha and chai's expect, I encountered a scenario where I needed to deeply compare an array of value objects to the parsed content of a JSON file.
The record object I am dealing with has approximately 20 properties, but currently only the price property can result in a mismatch. Upon inspection, I noticed that only five out of the twenty properties are affected by this mismatch.
expect(records).to.deep.equal(expected);
"data": {
- "price": 3578
+ "price": 3438
"not_important": "foo"
"also_not_important": "bar"
}
"data": {
- "price": 1828
+ "price": 1698
"not_important": "foo"
"also_not_important": "bar"
}
Although this default behavior is generally sufficient, it becomes challenging in cases like this one where it does not clearly indicate which specific data object is causing the assertions to fail, showing redundant data instead.
In such situations, having an 'important' property within the data object would greatly help in identifying the problematic expectation. Therefore, the ability to configure the displayed properties or to show the entire object in the diff would be highly beneficial.
Is there a way to customize mocha's diff display for scenarios like these?
To illustrate the issue further, here's a contrived meta-syntactic example:
import {expect} from "chai";
describe(("diff problem"), () => {
it("should demonstrate that the diff is not displayed properly", () => {
const actual = {
a: 1,
troiz: 0,
bar: 0,
baz: 2,
poit: 3,
narf: 4,
fizzbuzz: 117,
fizz: 5,
buzz: 4,
waldo: 115,
mos: 85465,
important: "THIS IS IMPORTANT",
};
const expected = {
...actual,
a: 0,
};
return expect(actual).to.deep.equal(expected);
});
});
The output of this testcase will typically show a limited diff, but it would be more helpful to display all relevant information including the 'important' property.
Here is an adjusted example focusing on deep equality comparison of arrays:
describe(("diff problem with an array"), () => {
it("should showcase the inadequate diff display for deep equal comparison of arrays", () => {
const anEntity = {
a: 1,
troiz: 0,
bar: 0,
baz: 2,
poit: 3,
narf: 4,
fizzbuzz: 117,
fizz: 5,
buzz: 4,
waldo: 115,
mos: 85465,
important: "IMPORTANT",
};
const offendingItem = {
...anEntity,
a: 0,
};
const actual = [
anEntity,
offendingItem,
anEntity,
];
const expected = [
anEntity,
anEntity,
anEntity,
];
return expect(actual).to.deep.equal(expected);
});
The resulting output may provide a partial diff, but adding Louis' suggested modification to chai still fails to highlight the crucial discrepancies effectively.