New matcher "hashContaining" similar to rspec's hash_including

This commit is contained in:
gvanhove
2011-03-09 18:56:28 -08:00
parent ce886e20e4
commit 992367dcbc
5 changed files with 188 additions and 0 deletions

View File

@@ -238,6 +238,14 @@ jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) {
return b.matches(a);
}
if (a instanceof jasmine.Matchers.HashContaining) {
return a.matches(b);
}
if (b instanceof jasmine.Matchers.HashContaining) {
return b.matches(a);
}
if (jasmine.isString_(a) && jasmine.isString_(b)) {
return (a == b);
}

View File

@@ -369,3 +369,32 @@ jasmine.Matchers.Any.prototype.toString = function() {
return '<jasmine.any(' + this.expectedClass + ')>';
};
jasmine.Matchers.HashContaining = function (sample) {
this.sample = sample;
};
jasmine.Matchers.HashContaining.prototype.matches = function(other, mismatchKeys, mismatchValues) {
mismatchKeys = mismatchKeys || [];
mismatchValues = mismatchValues || [];
var env = jasmine.getEnv();
var hasKey = function(obj, keyName) {
return obj != null && obj[keyName] !== jasmine.undefined;
};
for (var property in this.sample) {
if (!hasKey(other, property) && hasKey(this.sample, property)) {
mismatchKeys.push("expected has key '" + property + "', but missing from actual.");
}
else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) {
mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual.");
}
}
return (mismatchKeys.length === 0 && mismatchValues.length === 0);
};
jasmine.Matchers.HashContaining.prototype.toString = function () {
return "<jasmine.hashContaining(" + jasmine.pp(this.sample) + ")>";
};

View File

@@ -196,6 +196,21 @@ jasmine.any = function(clazz) {
return new jasmine.Matchers.Any(clazz);
};
/**
* Returns a matchable subset of a hash/JSON object. For use in expectations when you don't care about all of the
* attributes on the object.
*
* @example
* // don't care about any other attributes than foo.
* expect(mySpy).toHaveBeenCalledWith(jasmine.hashContaining({foo: "bar"});
*
* @param sample {Object} sample
* @returns matchable object for the sample
*/
jasmine.hashContaining = function (sample) {
return new jasmine.Matchers.HashContaining(sample);
};
/**
* Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks.
*