使用 mocha 测试对象是否部分包含在数组中

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

使用 Mocha 和 Chai,我通常使用 haveProperties 来测试一个对象是否部分包含另一个对象:

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

请注意 haveProperties 有效 "deeply" 甚至对于没有可枚举属性的对象,bartwinBar 被认为是相等的,尽管 barbaz 被认为是不同的。

现在,我需要知道我的部分对象是否包含在 array[=28= 中(使用 haveProperties 提供的深度相等约束) ] 个对象。

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


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

我不知道如何实现。

你试过了吗Chai Things

在你的情况下这应该有效(未测试)

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

试试这个:

 ownerArr.should.shallowDeepEqual(partial);

您可能需要执行 npm install chai-shallow-deep-equal 才能使上述工作正常

确保已安装 Chai Things 插件

另请参阅this。 link 中的第二个答案也应该有效。