Circular Reference in Snapshot
Error message
TypeError: Converting circular structure to JSON in snapshot
Quick summary
The object passed to toMatchSnapshot() has a circular reference (an object that references itself), which can't be serialized.
Why this happens
An object property points back to the object itself or a parent.
DOM nodes with parent/child references are being snapshotted.
Class instances with circular internal references.
React component instances with fiber node references.
Minimal example
test('snapshot', () => {
const obj = { a: 1 };
obj.self = obj; // circular reference
expect(obj).toMatchSnapshot(); // fails — circular
});test('snapshot', () => {
const obj = { a: 1 };
obj.self = obj;
const { a } = obj; // extract serializable part
expect({ a }).toMatchSnapshot(); // works
});Extract only the serializable parts of the object before snapshotting.
How to diagnose
Check if the object being snapshotted has circular references.
Use console.log(util.inspect(obj, { depth: null })) to see the structure.
Check if you're snapshotting a DOM node or React instance instead of serializable data.
How to fix
Snapshot only the serializable parts: expect(obj.serializablePart).toMatchSnapshot().
Use JSON.stringify with a replacer function to break circular references.
For DOM components, snapshot container.innerHTML instead of the container object.
Remove or break circular references before snapshotting.
How to prevent
Only snapshot serializable data (plain objects, arrays, strings).
Avoid snapshotting DOM nodes, class instances, or objects with circular refs.
Extract the relevant data into a plain object before snapshotting.
Related Resources
Related Glossary
Related Lessons
- Snapshot Testing
Using snapshots effectively.