[英]Unable to check a nested object property by using the “.nested” flag and bracket notation
Chai 4 and later's .nested.property()
was .deep.property()
in earlier versions. Chai 4和更高版本的
.nested.property()
.deep.property()
在早期版本中是.deep.property()
。 The issue I'm describing is present both with .nested.property()
in Chai 4 or later and with .deep.property()
in versions prior to 4. 我所描述的问题存在都与
.nested.property()
在湾仔4或更高版本,并与.deep.property()
在之前的版本4。
I've been trying to use the .nested
flag and bracket notation to check for the value of a nested property. 我一直在尝试使用
.nested
标志和方括号表示法来检查嵌套属性的值。 When I try to address into arrays, it works, but if I want to address into an object by doing "a['name']"
, it does not work. 当我尝试寻址到数组时,它可以工作,但是如果我想通过执行
"a['name']"
来寻址到对象,则它不起作用。 This is confusing because in JavaScript a.name
and a["name"]
would both refer to the same property, and in some cases we have to use the brackets due to the structure of the name. 这是令人困惑的,因为在JavaScript中
a.name
和a["name"]
都引用相同的属性,在某些情况下,由于名称的结构,我们必须使用方括号。
I have an example of the issue below. 我在下面有一个例子。 If you run this, you'll see
"first expect passed"
, but you won't see "second expect passed"
because the second assertion fails. 如果运行此命令,则将看到
"first expect passed"
,但不会看到"second expect passed"
因为第二个断言失败。
const { expect } = require("chai");
const obj = {
"a": ["foo", "bar"],
"b": { "foo-bar": 1},
};
expect(obj).to.have.nested.property("a[1]").equal("bar");
console.log("first expect passed");
expect(obj).to.have.nested.property("b['foo-bar']").equal(1);
console.log("second expect passed");
This is not clearly documented but the issue is that Chai is not actually interpreting the argument you pass to .property
in the exact same way a JavaScript interpreter would. 这不是明确记载,但问题是,柴实际上不解释,你传递给参数
.property
在完全相同的方式JavaScript解释会。 It is natural to go with b['foo-bar']
because that's what you'd expect you'd have to do if you were accessing the property in JavaScript code, but this won't work with Chai. 人们很自然地去
b['foo-bar']
因为这是你所期望的,你必须做,如果你在访问中的JavaScript代码的性质是什么,但是这不会与柴工作。 What you have to do is: 您要做的是:
expect(obj).to.have.nested.property("b.foo-bar").equal(1);
console.log("second expect passed");
The bracket notation in .property
is essentially only for addressing into arrays. .property
的括号符号基本上仅用于寻址到数组。 When it comes to objects you have to use the dot notation, even in cases where it would be invalid JavaScript. 对于对象,即使在无效的JavaScript情况下,也必须使用点符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.