Merge pull request #228 from duncanbeevers/deep_members

Deep equality check for collection membership
This commit is contained in:
Jake Luer 2014-01-29 17:20:33 -08:00
commit 407ce595b2
2 changed files with 25 additions and 6 deletions

View file

@ -1245,9 +1245,13 @@ module.exports = function (chai, _) {
);
});
function isSubsetOf(subset, superset) {
function isSubsetOf(subset, superset, cmp) {
return subset.every(function(elem) {
return superset.indexOf(elem) !== -1;
if (!cmp) return superset.indexOf(elem) !== -1;
return superset.some(function(elem2) {
return cmp(elem, elem2);
});
})
}
@ -1255,7 +1259,9 @@ module.exports = function (chai, _) {
* ### .members(set)
*
* Asserts that the target is a superset of `set`,
* or that the target and `set` have the same members.
* or that the target and `set` have the same strictly-equal (===) members.
* Alternately, if the `deep` flag is set, set members are compared for deep
* equality.
*
* expect([1, 2, 3]).to.include.members([3, 2]);
* expect([1, 2, 3]).to.not.include.members([3, 2, 8]);
@ -1263,6 +1269,8 @@ module.exports = function (chai, _) {
* expect([4, 2]).to.have.members([2, 4]);
* expect([5, 2]).to.not.have.members([5, 2, 1]);
*
* expect([{ id: 1 }]).to.deep.include.members([{ id: 1 }]);
*
* @name members
* @param {Array} set
* @param {String} message _optional_
@ -1276,9 +1284,11 @@ module.exports = function (chai, _) {
new Assertion(obj).to.be.an('array');
new Assertion(subset).to.be.an('array');
var cmp = flag(this, 'deep') ? _.eql : undefined;
if (flag(this, 'contains')) {
return this.assert(
isSubsetOf(subset, obj)
isSubsetOf(subset, obj, cmp)
, 'expected #{this} to be a superset of #{act}'
, 'expected #{this} to not be a superset of #{act}'
, obj
@ -1287,7 +1297,7 @@ module.exports = function (chai, _) {
}
this.assert(
isSubsetOf(obj, subset) && isSubsetOf(subset, obj)
isSubsetOf(obj, subset, cmp) && isSubsetOf(subset, obj, cmp)
, 'expected #{this} to have the same members as #{act}'
, 'expected #{this} to not have the same members as #{act}'
, obj

View file

@ -787,6 +787,15 @@ describe('expect', function () {
expect([5, 4]).not.members([]);
expect([5, 4]).not.members([6, 3]);
expect([5, 4]).not.members([5, 4, 2]);
})
expect([{ id: 1 }]).not.members([{ id: 1 }]);
});
it('deep.members', function() {
expect([{ id: 1 }]).deep.members([{ id: 1 }]);
expect([{ id: 2 }]).not.deep.members([{ id: 1 }]);
err(function(){
expect([{ id: 1 }]).deep.members([{ id: 2 }])
}, "expected [ { id: 1 } ] to have the same members as [ { id: 2 } ]");
});
});