tj / should.js

BDD style assertions for node.js -- test framework agnostic
MIT License
2.75k stars 195 forks source link

should.have.path for nested properties #207

Closed rprieto closed 10 years ago

rprieto commented 10 years ago

Testing nested properties, it seems we currently have a choice between:

person.address.city.should.eql('London')
//  cannot read property 'should' of undefined
//  expected 'Sydney' to equal 'London'

or the probably better option:

person.should.have.property('address')
             .have.property('city')
             .eql('London')

//  expected {} to have property 'city'
//  expected 'Sydney' to equal 'London'

That's better, but a little cumbersome, and still not quite as descriptive as I hoped. What if we could have:

person.should.have.path('address.city').eql('London')

//  expected { address: {} } to have property 'address.city'
//  expected { address: { city: 'Sydney'} } to have property 'address.city' equal to 'London' but was 'Sydney'

Alternatively, it could support JSONPath, in which case it's just a matter of executing the path and running the assertion of every match. The exception could (if possible) print the path of the failing properties.

person.should.have.path('.address.home.city').eql('London')
// expected {...} to have path 'address.home.city' but found none
// expected {...} to have path 'address.home.city' equal to 'London' but was 'Sydney'

person.should.have.path('.addresses[*].home.city').match(/[a-z]+/)
// expected {...} to have path 'addresses[2].home.city' matching /[a-z]+/ but was '123'

person.should.have.path('..age').above(30)
// expected {...} to have path 'kids[2].age' to be above 30 but was 12

Happy to give it a try for a PR, or make it a separate module if that's preferred.

btd commented 10 years ago

Idea is good, but i would like to do not add jsonpath as dependency. What i would suggest is something like this:

person.should.have.propertyByPath('address', 'home', 'city').eql('London')

(just path could confuse, i think)

rprieto commented 10 years ago

Fair point! For the syntax I guess the dot notation could be syntactic sugar that just calls String.split('.')

btd commented 10 years ago

I will close this as it already in master (will publish today or at weekend). If you have issues about it, pls create new one in shouldjs/should.js.

rprieto commented 10 years ago

That's great thanks! So is shouldjs/should.js taking over visionmedia/should.js as the official repo?

btd commented 10 years ago

Yes, i made TJ the admin of that org, i will add 2 others current maintainers as soon i reach them (but they are not too active to work on should.js).

ido-ran commented 9 years ago

+1