diff --git a/src/formatter/sortObject.js b/src/formatter/sortObject.js index c070ef612..5e6b8a46a 100644 --- a/src/formatter/sortObject.js +++ b/src/formatter/sortObject.js @@ -7,15 +7,18 @@ function safeSortObject(value: any, seen: WeakSet): any { return value; } - // return date, regexp and react element values as is - if ( - value instanceof Date || - value instanceof RegExp || - React.isValidElement(value) - ) { + // return date and regexp values as is + if (value instanceof Date || value instanceof RegExp) { return value; } + // return react element as is but remove _owner key because it can lead to recursion + if (React.isValidElement(value)) { + const copyObj = { ...value }; + delete copyObj._owner; + return copyObj; + } + seen.add(value); // make a copy of array with each item passed through the sorting algorithm @@ -27,9 +30,6 @@ function safeSortObject(value: any, seen: WeakSet): any { return Object.keys(value) .sort() .reduce((result, key) => { - if (key === '_owner') { - return result; - } if (key === 'current' || seen.has(value[key])) { // eslint-disable-next-line no-param-reassign result[key] = '[Circular]'; diff --git a/src/formatter/sortObject.spec.js b/src/formatter/sortObject.spec.js index 1b6ab3d45..182118e19 100644 --- a/src/formatter/sortObject.spec.js +++ b/src/formatter/sortObject.spec.js @@ -1,5 +1,6 @@ /* @flow */ +import React from 'react'; import sortObject from './sortObject'; describe('sortObject', () => { @@ -42,4 +43,49 @@ describe('sortObject', () => { c: date, }); }); + + describe('_owner key', () => { + it('should preserve the _owner key for objects that are not react elements', () => { + const fixture = { + _owner: "_owner that doesn't belong to react element", + foo: 'bar', + }; + + expect(JSON.stringify(sortObject(fixture))).toEqual( + JSON.stringify({ + _owner: "_owner that doesn't belong to react element", + foo: 'bar', + }) + ); + }); + + it('should remove the _owner key from top level react element', () => { + const fixture = { + reactElement: ( +
+ +
+ ), + }; + + expect(JSON.stringify(sortObject(fixture))).toEqual( + JSON.stringify({ + reactElement: { + type: 'div', + key: null, + props: { + children: { + type: 'span', + key: null, + props: {}, + _owner: null, + _store: {}, + }, + }, + _store: {}, + }, + }) + ); + }); + }); });