Skip to content

Commit

Permalink
fix: stringifying elements with props containing circular references (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Andarist authored Oct 19, 2021
1 parent 25695c3 commit f203060
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/formatter/sortObject.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* @flow */
import * as React from 'react';

export default function sortObject(value: any): any {
function safeSortObject(value: any, seen: WeakSet<any>): any {
// return non-object value as is
if (value === null || typeof value !== 'object') {
return value;
Expand All @@ -16,9 +16,11 @@ export default function sortObject(value: any): any {
return value;
}

// make a copy of array with each item passed through sortObject()
seen.add(value);

// make a copy of array with each item passed through the sorting algorithm
if (Array.isArray(value)) {
return value.map(sortObject);
return value.map(v => safeSortObject(v, seen));
}

// make a copy of object with key sorted
Expand All @@ -28,13 +30,17 @@ export default function sortObject(value: any): any {
if (key === '_owner') {
return result;
}
if (key === 'current') {
if (key === 'current' || seen.has(value[key])) {
// eslint-disable-next-line no-param-reassign
result[key] = '[Circular]';
} else {
// eslint-disable-next-line no-param-reassign
result[key] = sortObject(value[key]);
result[key] = safeSortObject(value[key], seen);
}
return result;
}, {});
}

export default function sortObject(value: any): any {
return safeSortObject(value, new WeakSet());
}
19 changes: 19 additions & 0 deletions src/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1355,4 +1355,23 @@ describe('reactElementToJSXString(ReactElement)', () => {
]}
/>`);
});

it('should stringify element with a prop that has circular references', () => {
const parent = {};
const child = {};
parent.child = child;
child.parent = parent;

function Comp() {
return null;
}

expect(reactElementToJSXString(<Comp prop={parent} />)).toEqual(`<Comp
prop={{
child: {
parent: '[Circular]'
}
}}
/>`);
});
});

0 comments on commit f203060

Please sign in to comment.