From 6324fda0650e9989f456424eaedb0d625d2b4abf Mon Sep 17 00:00:00 2001 From: johnjbarton Date: Thu, 27 Jun 2019 10:35:59 -0700 Subject: [PATCH] PrettyPrinter survives if objects throw in toString --- spec/core/PrettyPrintSpec.js | 10 ++++++++-- src/core/PrettyPrinter.js | 21 +++++++++++++++------ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/spec/core/PrettyPrintSpec.js b/spec/core/PrettyPrintSpec.js index 0e3c48ad..1249d8c6 100644 --- a/spec/core/PrettyPrintSpec.js +++ b/spec/core/PrettyPrintSpec.js @@ -457,11 +457,17 @@ describe('jasmineUnderTest.pp', function() { // Valid: an actual number baz: 3, // Valid: an actual Error object - qux: new Error('bar') + qux: new Error('bar'), + // + baddy: { + toString: function() { + throw new Error('I am a bad toString'); + } + } }; expect(jasmineUnderTest.pp(obj)).toEqual( - 'Object({ foo: [object Number], bar: [object Object], baz: 3, qux: Error: bar })' + 'Object({ foo: [object Number], bar: [object Object], baz: 3, qux: Error: bar, baddy: has-invalid-toString-method })' ); }); }); diff --git a/src/core/PrettyPrinter.js b/src/core/PrettyPrinter.js index 67cb34d6..e01afc80 100644 --- a/src/core/PrettyPrinter.js +++ b/src/core/PrettyPrinter.js @@ -9,11 +9,16 @@ getJasmineRequireObj().pp = function(j$) { function hasCustomToString(value) { // value.toString !== Object.prototype.toString if value has no custom toString but is from another context (e.g. // iframe, web worker) - return ( - j$.isFunction_(value.toString) && - value.toString !== Object.prototype.toString && - value.toString() !== Object.prototype.toString.call(value) - ); + try { + return ( + j$.isFunction_(value.toString) && + value.toString !== Object.prototype.toString && + value.toString() !== Object.prototype.toString.call(value) + ); + } catch (e) { + // The custom toString() threw. + return true; + } } PrettyPrinter.prototype.format = function(value) { @@ -59,7 +64,11 @@ getJasmineRequireObj().pp = function(j$) { !j$.isArray_(value) && hasCustomToString(value) ) { - this.emitScalar(value.toString()); + try { + this.emitScalar(value.toString()); + } catch (e) { + this.emitScalar('has-invalid-toString-method'); + } } else if (j$.util.arrayContains(this.seen, value)) { this.emitScalar( '