Added support for custom object formatters
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.
This commit is contained in:
committed by
Steve Gravrock
parent
1f23f1e4d2
commit
25816a6e77
@@ -1,12 +1,13 @@
|
||||
getJasmineRequireObj().DiffBuilder = function(j$) {
|
||||
return function DiffBuilder() {
|
||||
return function DiffBuilder(config) {
|
||||
var path = new j$.ObjectPath(),
|
||||
mismatches = [];
|
||||
mismatches = [],
|
||||
prettyPrinter = (config || {}).prettyPrinter || j$.makePrettyPrinter();
|
||||
|
||||
return {
|
||||
record: function (actual, expected, formatter) {
|
||||
formatter = formatter || defaultFormatter;
|
||||
mismatches.push(formatter(actual, expected, path));
|
||||
mismatches.push(formatter(actual, expected, path, prettyPrinter));
|
||||
},
|
||||
|
||||
getMessage: function () {
|
||||
@@ -21,12 +22,12 @@ getJasmineRequireObj().DiffBuilder = function(j$) {
|
||||
}
|
||||
};
|
||||
|
||||
function defaultFormatter (actual, expected, path) {
|
||||
function defaultFormatter (actual, expected, path, prettyPrinter) {
|
||||
return 'Expected ' +
|
||||
path + (path.depth() ? ' = ' : '') +
|
||||
j$.pp(actual) +
|
||||
prettyPrinter(actual) +
|
||||
' to equal ' +
|
||||
j$.pp(expected) +
|
||||
prettyPrinter(expected) +
|
||||
'.';
|
||||
}
|
||||
};
|
||||
|
||||
@@ -45,7 +45,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
|
||||
if (i > 0) {
|
||||
message += ',';
|
||||
}
|
||||
message += ' ' + j$.pp(expected[i]);
|
||||
message += ' ' + self.pp(expected[i]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ getJasmineRequireObj().toEqual = function(j$) {
|
||||
var result = {
|
||||
pass: false
|
||||
},
|
||||
diffBuilder = j$.DiffBuilder();
|
||||
diffBuilder = j$.DiffBuilder({prettyPrinter: util.pp});
|
||||
|
||||
result.pass = util.equals(actual, expected, diffBuilder);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user