gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:38:36 26 4
gpt4 key购买 nike

我在 mocha JS 测试框架中使用 chai.js expectations。我正在尝试测试数组中对象的包含情况,但 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}]和matchee {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});

关于javascript - 为什么数组包含检查在 chai.js 中没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com