diff --git a/spec/core/PrettyPrintSpec.js b/spec/core/PrettyPrintSpec.js index 47a5758a..64dea0fd 100644 --- a/spec/core/PrettyPrintSpec.js +++ b/spec/core/PrettyPrintSpec.js @@ -333,4 +333,27 @@ describe("jasmineUnderTest.pp", function () { expect(jasmineUnderTest.pp(obj)).toEqual("null({ foo: 'bar' })"); }); + + it("should gracefully handle objects with invalid toString implementations", function () { + var obj = { + foo: { + toString: function() { + // Invalid: toString returning a number + return 3; + } + }, + bar: { + toString: function() { + // Invalid: toString returning an object + return new Error("bar"); + } + }, + // Valid: an actual number + baz: 3, + // Valid: an actual Error object + qux: new Error("bar") + }; + + expect(jasmineUnderTest.pp(obj)).toEqual("Object({ foo: [object Number], bar: [object Error], baz: 3, qux: Error: bar })"); + }); }); diff --git a/src/core/PrettyPrinter.js b/src/core/PrettyPrinter.js index cb738d28..42b89784 100644 --- a/src/core/PrettyPrinter.js +++ b/src/core/PrettyPrinter.js @@ -266,6 +266,12 @@ getJasmineRequireObj().pp = function(j$) { }; PrettyPrinter.prototype.append = function(value) { + // This check protects us from the rare case where an object has overriden + // `toString()` with an invalid implementation (returning a non-string). + if (typeof value !== 'string') { + value = Object.prototype.toString.call(value); + } + var result = truncate(value, j$.MAX_PRETTY_PRINT_CHARS - this.length); this.length += result.value.length; this.stringParts.push(result.value);