2

Working with Mocha and Chai, I'm usually using haveProperties to test if an object partially contains another object:

class Foo {
    constructor(value) {
        Object.defineProperty(this, '_str', {
            value
        });
    }

    toString() {
        return this._str;
    }
}

const bar = new Foo('bar');
const twinBar = new Foo('bar');
const baz = new Foo('baz');

const owner = {
    a: 4,
    b: bar,
    c: 7
};

const partial1 = {
    a: 4,
    b: twinBar
};

const partial2 = {
    a: 4,
    b: baz
};


owner.should.haveProperties(partial1); // success
owner.should.haveProperties(partial2); // failure

Notice that haveProperties works "deeply" and even for objects that do not have enumerable properties, bar and twinBar are considered equals although bar and baz are considered different.

Now, I'm in a situation where I need to know if my partial object is included (with the deep equality constraint provided by haveProperties) into an array of objects.

const ownerArr = [{
    a: 4,
    b: bar,
    c: 7
}, {
    a: 3
}];


ownerArr.should.(????)(partial1); // should succeed
ownerArr.should.(????)(partial2); // should fail

And I don't have any idea how to achieve that.

Guid
  • 2,137
  • 2
  • 20
  • 33

1 Answers1

1

Have you tried Chai Things

In your case this should work (not tested)

ownerArr.should.include.something.that.deep.equals(partial)

try this:

 ownerArr.should.shallowDeepEqual(partial);

You may have to do npm install chai-shallow-deep-equal for above to work

make sure that Chai Things plugin is installed

Also look at this. second answer in that link should also work.

Community
  • 1
  • 1
user1207289
  • 3,060
  • 6
  • 30
  • 66
  • `AssertionError: expected an element of [ Array(2) ] to deeply equal { a: 4, b: { d: 3 } } ` – Guid Sep 08 '16 at 14:19
  • Thanks! It indeed works perfectly with my example but I realize that in my true project, I have some properties of my objects that have no enumerable properties and so it always assert to true, even if my objects are differents :( – Guid Sep 08 '16 at 15:45
  • @Guid Glad it works for you , can you mark it as answer. You have to include actual code for someone to be look. – user1207289 Sep 08 '16 at 16:01
  • @Guid , ideally you should mark this as answer , keeping everything same as previously in question and open new question for new doubts. – user1207289 Sep 08 '16 at 16:50