diff --git a/lib/object.js b/lib/object.js index b35b9c8..4cbb87f 100644 --- a/lib/object.js +++ b/lib/object.js @@ -7,6 +7,11 @@ export default function inspectObject(object, options) { return '{}' } options.truncate -= 4 + options.seen = options.seen || [] + if (options.seen.indexOf(object) >= 0) { + return '[Circular]' + } + options.seen.push(object) const propertyContents = inspectList( properties.map(key => [key, object[key]]), options, @@ -17,6 +22,7 @@ export default function inspectObject(object, options) { options, inspectProperty ) + options.seen.pop() let sep = '' if (propertyContents && symbolContents) { sep = ', ' diff --git a/test/objects.js b/test/objects.js index 877f550..aea8014 100644 --- a/test/objects.js +++ b/test/objects.js @@ -10,6 +10,14 @@ for (const [suite, inspect] of Object.entries({ expect(inspect({})).to.equal('{}') }) + if (suite === 'objects') { + it('detects circular references', () => { + const main = {} + main.a = main + expect(inspect(main)).to.equal('{ a: [Circular] }') + }) + } + describe('truncate', () => { it('returns the full representation when truncate is over string length', () => { expect(inspect({ a: 1, b: 2, c: 3 }, { truncate: 20 })).to.equal('{ a: 1, b: 2, c: 3 }')