Guid
Guid

Reputation: 2216

Test if a object is partially included into an array with mocha

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.

Upvotes: 2

Views: 1193

Answers (1)

user1207289
user1207289

Reputation: 3253

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.

Upvotes: 1

Related Questions