From 604cd6132f71f6e4d7e5ceb303efde28bdf61450 Mon Sep 17 00:00:00 2001 From: Pivotal Date: Mon, 25 Apr 2016 12:23:56 -0400 Subject: [PATCH] Prettyprint objects whose constructors have custom toString method - when the constructor has a name, print the name - when the constructor does not have a name, print `` [Fixes issue 1019](https://github.com/jasmine/jasmine/issues/1019) --- spec/core/PrettyPrintSpec.js | 20 ++++++++++++++++++++ src/core/base.js | 7 ++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/spec/core/PrettyPrintSpec.js b/spec/core/PrettyPrintSpec.js index 7290db01..4783ac4e 100644 --- a/spec/core/PrettyPrintSpec.js +++ b/spec/core/PrettyPrintSpec.js @@ -189,6 +189,26 @@ describe("jasmineUnderTest.pp", function () { expect(jasmineUnderTest.pp(obj)).toEqual("my toString"); }); + it("should stringify objects from named constructors with custom toString", function () { + var MyNamedConstructor = function MyNamedConstructor () {}; + MyNamedConstructor.toString = function () { return ""; }; + + var a = {}; + a.constructor = MyNamedConstructor; + + expect(jasmineUnderTest.pp(a)).toEqual("MyNamedConstructor({ constructor: Function })"); + }); + + it("should stringify objects from anonymous constructors with custom toString", function () { + var MyAnonymousConstructor = function () {}; + MyAnonymousConstructor.toString = function () { return ""; }; + + var a = {}; + a.constructor = MyAnonymousConstructor; + + expect(jasmineUnderTest.pp(a)).toEqual("({ constructor: Function })"); + }); + it("should handle objects with null prototype", function() { if (jasmine.getEnv().ieVersion < 9) { return; } diff --git a/src/core/base.js b/src/core/base.js index 418a690f..dfb0f1c8 100644 --- a/src/core/base.js +++ b/src/core/base.js @@ -38,7 +38,12 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; j$.fnNameFor = function(func) { - return func.name || func.toString().match(/^\s*function\s*(\w*)\s*\(/)[1]; + if (func.name) { + return func.name; + } + + var matches = func.toString().match(/^\s*function\s*(\w*)\s*\(/); + return matches ? matches[1] : ''; }; j$.any = function(clazz) {