Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep Object Equality of only own Object's Properties in Chai

I have an object that I would like to do a deep comparison against another object in chaijs. The trouble is that one object has a large number of enumerable properties and the other object is a simple, straightforward object ({}).

For example, I have expect(obj1).to.eql(obj2); where obj1 is an object with many additional enumerable properties that a library added and obj2 was simply created via var obj2 = { someValue: true }.

This problem can be solved by abusing JSON.stringify and JSON.parse like so

expect(JSON.parse(JSON.stringify(obj1))).to.eql(obj2);

but that is a pretty lame hack. I can't image that I am the first one to run into this predicament but my searches have turned up empty. What is the recommended approach here?

like image 542
mark Avatar asked Jul 10 '15 06:07

mark


1 Answers

You can try to use chai-shallow-deep-equal. It does not perform full equality check, but check that second object contains set of properties of first object.

Here's usage example:

var chai = require('chai');
chai.use(require('chai-shallow-deep-equal'));

var obj1 = {name: 'Michel', language: 'javascript'};
var obj2 = {name: 'Michel'};
var obj3 = {name: 'Michel', age: 43};

expect(obj1).to.shallowDeepEqual(obj2); // true
expect(obj1).to.shallowDeepEqual(obj3); // false, age is undefined in obj1
like image 187
edufinn Avatar answered Sep 20 '22 13:09

edufinn