I'm using Chai.js and I'm trying to check if an object contains a partial key. Let me explain:
I have this object to test:
var obj = {
"one/two/three": "value"
}
And I want to check using Chai.js if the object obj
contains a partial key "one"
which is include in the key "one/two/three"
.
Here I check that a key is included:
({ foo: 1, bar: 2 }).should.have.keys('bar');
({ foo: 1, bar: 2, baz: 3 }).should.include.keys('foo');
({ foo: 1, bar: 2, baz: 3 }).should.contain.keys('baz');
And here I check if a string contains a substring:
'foobar'.should.match(/^foo/)
Then, I would like to merge both to have something like this:
({ foo: 1, bar: 2, baz: 3 }).should.contain.keys.which.match('fo');
Do you know a way to handle this?
Thanks for your help!
I'm using Chai.js and I'm trying to check if an object contains a partial key. Let me explain:
I have this object to test:
var obj = {
"one/two/three": "value"
}
And I want to check using Chai.js if the object obj
contains a partial key "one"
which is include in the key "one/two/three"
.
Here I check that a key is included:
({ foo: 1, bar: 2 }).should.have.keys('bar');
({ foo: 1, bar: 2, baz: 3 }).should.include.keys('foo');
({ foo: 1, bar: 2, baz: 3 }).should.contain.keys('baz');
And here I check if a string contains a substring:
'foobar'.should.match(/^foo/)
Then, I would like to merge both to have something like this:
({ foo: 1, bar: 2, baz: 3 }).should.contain.keys.which.match('fo');
Do you know a way to handle this?
Thanks for your help!
Share Improve this question asked Sep 30, 2016 at 8:29 BarudarBarudar 5704 silver badges13 bronze badges 2- I'd be very surprised if Chai has a built-in assertion for this, but its documentation does talk about how to add your own. Adding your own for the above would be fairly trivial. – T.J. Crowder Commented Sep 30, 2016 at 8:31
- I've just found docs about creating my own, looks like interesting, thanks! – Barudar Commented Sep 30, 2016 at 8:38
1 Answer
Reset to default 3The simplest way I can think of to do this is iterate over the Object's keys and check if any of them match the regular expression.
Object.keys({ foo: 1, bar: 2, baz: 3 }).some(function(key) {
if (key.match(/^foo/) != null) {
return true;
}
return false;
});
You can then wrap this in some chai code to achieve the desired result like so:
expect(Object.keys({ foo: 1, bar: 2, baz: 3 }).some(function(key) {
if (key.match(/^foo/) != null) {
return true;
}
return false;
})).to.equal(true);
In case you're unfamiliar with Array.some, it will immediately return true as soon as it reaches any key that causes its callback to return a truthy value.