Skip to content

Commit

Permalink
Extended keys documentation and set bools instead of changing flags i…
Browse files Browse the repository at this point in the history
…n the keys assertion
  • Loading branch information
root committed Dec 3, 2014
1 parent b037bb5 commit 1718d20
Showing 1 changed file with 27 additions and 13 deletions.
40 changes: 27 additions & 13 deletions lib/chai/core/assertions.js
Original file line number Diff line number Diff line change
Expand Up @@ -965,12 +965,24 @@ module.exports = function (chai, _) {
/**
* ### .keys(key1, [key2], [...])
*
* Asserts that the target has exactly the given keys, or
* asserts the inclusion of some keys when using the
* `include` or `contain` modifiers.
*
* expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']);
* expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar');
* Asserts that the target contains any or all of the passed-in keys.
* When used in conjunction with `all`, every key that is passed in
* must exist in the target object.
*
* When used in conjunction with `any`, at least one key that is passed
* in must exist in the target object. Use without the `any` or `all`
* qualifiers is deprecated and will default to `all`.
*
* Finally, use of `contains` in conjunction with `all` requires that
* the number of passed-in keys match the total number of keys in the target
* object.
*
* expect({ foo: 1, bar: 2 }).to.have.any.keys('foo', 'baz');
* expect({ foo: 1, bar: 2 }).to.have.any.keys('foo');
* expect({ foo: 1, bar: 2 }).to.contain.any.keys('bar', 'baz');
* expect({ foo: 1, bar: 2 }).to.contain.any.keys(['foo']);
* expect({ foo: 1, bar: 2 }).to.have.all.keys(['bar', 'foo']);
* expect({ foo: 1, bar: 2 }).to.contain.all.keys(['bar', 'foo']);
*
* @name keys
* @alias key
Expand All @@ -991,22 +1003,24 @@ module.exports = function (chai, _) {

var actual = Object.keys(obj)
, expected = keys
, len = keys.length;
, len = keys.length
, any = flag(this, 'any')
, all = flag(this, 'all');

if (!flag(this, 'any') && !flag(this, 'all')) {
flag(this, 'all', true);
if (!any && !all) {
all = true;
}

// Has any
if (flag(this, 'any')) {
if (any) {
var intersection = expected.filter(function(key) {
return ~actual.indexOf(key);
});
ok = intersection.length > 0;
}

// Has all
if (flag(this, 'all')) {
if (all) {
ok = keys.every(function(key){
return ~actual.indexOf(key);
});
Expand All @@ -1021,10 +1035,10 @@ module.exports = function (chai, _) {
return _.inspect(key);
});
var last = keys.pop();
if (flag(this, 'all')) {
if (all) {
str = keys.join(', ') + ', and ' + last;
}
if (flag(this, 'any')) {
if (any) {
str = keys.join(', ') + ', or ' + last;
}
} else {
Expand Down

0 comments on commit 1718d20

Please sign in to comment.