From 0d0972a59e6e0354033c9fdfec72d5ddfbfe8e1e Mon Sep 17 00:00:00 2001 From: Jakub Z Date: Fri, 18 Jul 2014 13:54:39 +0100 Subject: [PATCH] fix(client): Fix stringify serializing objects Serialize uses the name of the constructor to serialize objects. When the object was created using Object.create(null) or has a property constructor this may throw an Error --- client/stringify.js | 9 +++++++-- test/client/stringify.spec.js | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/client/stringify.js b/client/stringify.js index 1c5a46c7d..5920587fd 100644 --- a/client/stringify.js +++ b/client/stringify.js @@ -39,11 +39,16 @@ var stringify = function stringify(obj, depth) { } else if (obj.outerHTML) { return obj.outerHTML; } else { - strs.push(obj.constructor.name); + var constructor = 'Object'; + if (obj.constructor && typeof obj.constructor === 'function') { + constructor = obj.constructor.name; + } + + strs.push(constructor); strs.push('{'); var first = true; for (var key in obj) { - if (obj.hasOwnProperty(key)) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { if (first) { first = false; } else { diff --git a/test/client/stringify.spec.js b/test/client/stringify.spec.js index 3ea1bdd22..140d878ac 100644 --- a/test/client/stringify.spec.js +++ b/test/client/stringify.spec.js @@ -32,6 +32,28 @@ describe('stringify', function() { expect(stringify(['a', 'b', null, true, false])).toBe("['a', 'b', null, true, false]"); }); + it('should serialize objects', function () { + var obj; + + + obj = {a: 'a', b: 'b', c: null, d: true, e: false}; + expect(stringify(obj)).toBe('Object{a: \'a\', b: \'b\', c: null, d: true, e: false}'); + + function MyObj() { + this.a = 'a'; + } + + obj = new MyObj(); + expect(stringify(obj)).toBe('MyObj{a: \'a\'}'); + + obj = {constructor: null}; + expect(stringify(obj)).toBe('Object{constructor: null}'); + + obj = Object.create(null); + obj.a = 'a'; + expect(stringify(obj)).toBe('Object{a: \'a\'}'); + }); + it('should serialize html', function() { var div = document.createElement('div');