Custom object formatters allow users to customize how an object is
stringified in matcher failure messages. This can already be done by
adding a `jasmineToString` method to the objects in question. But
it's not always desirable or possible to do that, particularly when
objects of a given "type" do not inherit from a specific prototype.
For instance, suppose a web service returns a list of foos that are
deserialized from JSON, e.g.:
{ fooId: 42, /* more properties */ }
The only way to define `jasmineToString` on those is by writing code to
add it to each instance at runtime. But a custom object formatter can
recognize that the object it's looking at is a foo and format it
accordingly:
jasmine.addCustomObjectFormatter(function(obj) {
if (typeof obj.fooId !== 'number') {
return undefined;
}
return '[Foo with ID ' + obj.fooId + ']';
});
Unlike `jasmineToString`, custom object formatters are scoped to a
particular spec or suite and don't require any changes to the code
under test.
40 lines
1.1 KiB
JavaScript
40 lines
1.1 KiB
JavaScript
getJasmineRequireObj().SetContaining = function(j$) {
|
|
function SetContaining(sample) {
|
|
if (!j$.isSet(sample)) {
|
|
throw new Error('You must provide a set to `setContaining`, not ' + j$.pp(sample));
|
|
}
|
|
|
|
this.sample = sample;
|
|
}
|
|
|
|
SetContaining.prototype.asymmetricMatch = function(other, matchersUtil) {
|
|
if (!j$.isSet(other)) return false;
|
|
|
|
var hasAllMatches = true;
|
|
j$.util.forEachBreakable(this.sample, function(breakLoop, item) {
|
|
// for each item in `sample` there should be at least one matching item in `other`
|
|
// (not using `matchersUtil.contains` because it compares set members by reference,
|
|
// not by deep value equality)
|
|
var hasMatch = false;
|
|
j$.util.forEachBreakable(other, function(oBreakLoop, oItem) {
|
|
if (matchersUtil.equals(oItem, item)) {
|
|
hasMatch = true;
|
|
oBreakLoop();
|
|
}
|
|
});
|
|
if (!hasMatch) {
|
|
hasAllMatches = false;
|
|
breakLoop();
|
|
}
|
|
});
|
|
|
|
return hasAllMatches;
|
|
};
|
|
|
|
SetContaining.prototype.jasmineToString = function(pp) {
|
|
return '<jasmine.setContaining(' + pp(this.sample) + ')>';
|
|
};
|
|
|
|
return SetContaining;
|
|
};
|