Chai deep contains assertion on nested objects

2019-06-20 10:35发布

问题:

I'm trying to assert that a object contains another one(e.i. deep equal cannot be use), but it seems that the nested ones are checked strictly.

Code example:

describe('Meta', function () {
    it('object should contains a cloned copy', function () {
        var obj = {a: 1, b: '2', c: {a: 2, b: '2'}};
        return expect(obj).deep.contains(JSON.parse(JSON.stringify(obj)));
    });
});

Error message:

AssertionError: expected { a: 1, b: '2', c: { a: 2, b: '2' } } to have a property 'c' of { a: 2, b: '2' }, but got { a: 2, b: '2' }

Is there any way to do a "contains" with "deep equal" functionality?

回答1:

Instead of using contains, try using eql:

expect(obj).to.deep.eql(JSON.parse(JSON.stringify(obj)));

eql compares the values in the object.

That should do the trick.