Uniform equality of objects only in object properties in Chai
I have an object that would like to do a deep comparison with another object in chaijs . The problem is that one object has a large number of enumerable properties, and the other object is a plain, simple object ( {}
).
For example, I have expect(obj1).to.eql(obj2);
, where obj1
is an object with many additional enumerable properties added to the library and obj2
was just created via var obj2 = { someValue: true }
.
This problem can be solved by abuse JSON.stringify
and JSON.parse
as follows
expect(JSON.parse(JSON.stringify(obj1))).to.eql(obj2);
but that's a pretty lame hack. I cannot imagine that I am the first to run into this predicament, but my search has been empty. What's the recommended approach here?
source to share
I would suggest making a projection of the object you want to test that only contains "own" (not from prototype properties) properties and compares that for equality.
var projection = {};
for (var key in obj1) {
if (obj1.hasOwnProperty(key)) {
projection[key] = obj1[key];
}
}
expect(projection).to.eql(obj2);
You can extract this projection code into a test utility function.
source to share
You can try to use chai-shallow-deep-equal . It does not perform a full equality check, but it verifies that the second object contains the set of properties of the first object.
Here's a usage example:
var chai = require('chai');
chai.use(require('chai-shallow-deep-equal'));
var obj1 = {name: 'Michel', language: 'javascript'};
var obj2 = {name: 'Michel'};
var obj2 = {name: 'Michel', age: 43};
expect(obj1).to.shallowDeepEqual(obj2); // true
expect(obj1).to.shallowDeepEqual(obj3); // false, age is undefined in obj1
source to share