为什么数组包含检查在 chai.js 中没有按预期工作?

Why don't array include checks work as expected in chai.js?

我在 mocha JS 测试框架中使用 chai.js 期望值。我正在尝试测试数组中是否包含对象,但 chai 在其文档中支持的 includes 行为似乎没有像我预期的那样工作:

chai 网站上的例子是 this:

expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2});

按预期工作。但是,以下失败:

expect([{a: 1}]).to.be.an('array').and.include({a: 1})

错误:

(node:5639) ... AssertionError: expected [ { a: 1 } ] to include { a: 1 }

但这成功了:

expect([1,2]).to.be.an('array').and.include(1)

我做错了什么?

根据文档:

When the target is an array, .include asserts that the given val is a member of the target.

很明显,数组成员[{a: 1}]和匹配对象{a: 1}是两个不同的对象。因此匹配对象不是目标的成员。另一方面,基元是使用它们的值而不是它们的引用来匹配的。因此以下断言通过:

expect([1,2]).to.be.an('array').and.include(1)

对于对象,文档说:

When the target is an object, .include asserts that the given object val’s properties are a subset of the target’s properties.

这意味着 chai 实际上会检查两个对象之间每个 属性 的值相似性。这就是断言也通过那里的原因。

要更正此问题,您可以声明变量一次,然后在两个地方都使用它:

var obj = {a: 1};
expect([obj]).to.be.an('array').and.include(obj);

或者,您可以在目标数组中 deep check 像这样:

expect([{a: 1}]).to.deep.include({a: 1});