简体   繁体   中英

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. 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.

I've been trying to use the .nested flag and bracket notation to check for the value of a nested property. 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. 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.

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.

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. 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. 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. When it comes to objects you have to use the dot notation, even in cases where it would be invalid JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM