Skip to content

Commit

Permalink
feat: handles inspection of objects with circular references (#47)
Browse files Browse the repository at this point in the history
Fix #44
  • Loading branch information
pcorpet authored Jun 24, 2021
1 parent 5e76830 commit 1664d70
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -17,6 +22,7 @@ export default function inspectObject(object, options) {
options,
inspectProperty
)
options.seen.pop()
let sep = ''
if (propertyContents && symbolContents) {
sep = ', '
Expand Down
8 changes: 8 additions & 0 deletions test/objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }')
Expand Down

0 comments on commit 1664d70

Please sign in to comment.