question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

query* causes TypeError: Converting circular structure to JSON

See original GitHub issue

EDIT: Updated to reflect my latest findings

  • @testing-library/dom version: 7.29.4
  • Testing Framework and version: Jest 26.6.3
  • DOM Environment: jsdom 16.4.0
  • React version: happens on both 16.13.1 and 17.0.1
  • Node version: v12.18.3

Relevant code or config:

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';

describe('test test', () => {
  it('example test', () => {
    const { queryAllByText } = render(
      <div>
        <div>test thing</div>
        <div>test thing</div>
      </div>
    );
    expect(queryAllByText('test thing')).toEqual(123);
  });
});

What you did:

I was trying to query deep element for clicking it. The page contains two matching components with the same text

What happened:

I’m getting following:

(node:38467) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'HTMLDivElement'
    |     property '__reactInternalInstance$e23phu313qm' -> object with constructor 'FiberNode'
    --- property 'stateNode' closes the circle
    at stringify (<anonymous>)
    at writeChannelMessage (internal/child_process/serialization.js:117:20)
    at process.target._send (internal/child_process.js:779:17)
    at process.target.send (internal/child_process.js:677:19)
    at reportSuccess (/Users/path/to/project/node_modules/jest-runner/node_modules/jest-worker/build/workers/processChild.js:67:11)

Reproduction:

  1. run the above example with jest --watch (babel and jest configs can be very basic or even default)
  2. either restart Jest, or change the file to trigger second run
  3. You should get the error above

The error happens when Jest runs the snippet for second time or more. It can be resolved by wiping the query cache using jest --clearCache, but it reappears on second test run.

Problem description:

The test crashes and leaves Jest hanging. This does not happen if I’m not querying the component with anything, but does happen when querying, at least with queryByText and queryAllByText.

Suggested solution:

The above example should not crash. I hope the stacktrace and the description gives enough clue on what might be the culprit here.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:8
  • Comments:25 (8 by maintainers)

github_iconTop GitHub Comments

4reactions
Chamioncommented, May 12, 2021

The error seems to happen when HTML elements are passed to expect as a value to be compared. When an assertion fails jest tries to format the test output and somewhere along the way it passes the argument of expect to JSON.stringify. The elements contain circular references so stringifying throws.

Here’s a crude monkeypatch to delete the circular reference when making assertions. It doesn’t handle all cases and might have side-effects but it was good enough for my use case and hopefully highlights where the issue lies.

In global setup file (“setupFilesAfterEnv”):

const removeReactInternalInstance = element => {
  const keys = Object.keys(element);
  const reactInternalInstanceKey = keys.find(key => /^__reactInternalInstance/.test(key));
  if (reactInternalInstanceKey != null) delete element[reactInternalInstanceKey];
};
const { expect } = window;
window.expect = (actual, ...rest) => {
  if (typeof actual === 'object' && actual !== null) {
    if (Array.isArray(actual)) {
      actual.forEach(removeReactInternalInstance);
    } else {
      removeReactInternalInstance(actual);
    }
  }
  return expect(actual, ...rest);
};
Object.entries(expect).forEach(([key, value]) => window.expect[key] = value);

I would argue this is a bug in Jest rather than a bug in testing-library. Jest should be able to format objects with circular references or at least give an informative error message.

2reactions
kreslicommented, Jun 23, 2021

Isn’t that because query is actually a Promise? image

doing so will fail

image

but this works

image

Maybe this would help someone:

// if expect do not exist
await expect(screen.findByTestId(contextMenuId)).rejects.toThrowError();
// expect it exist
await expect(screen.findByTestId(contextMenuId)).resolves.toBeDefined();
Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeError: Converting circular structure to JSON - Stack ...
It means that the object you pass in the request (I guess it is pagedoc ) has a circular reference, something like: var...
Read more >
TypeError: Converting circular structure to JSON in JS
The "Converting circular structure to JSON" error occurs when we pass an object that contains circular references to the JSON.stringify() method.
Read more >
How to fix TypeError: Converting circular structure to JSON in ...
To fix this error, you need to make sure that your objects don't contain circular references. One way to do this is to...
Read more >
unhandledpromiserejectionwarni...
StackOverflow ; (node:10672) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON ; --> starting at object with constructor 'Object' ...
Read more >
TypeError: cyclic object value - JavaScript - MDN Web Docs
TypeError : Converting circular structure to JSON (V8-based) ... how to find and filter (thus causing data loss) a cyclic reference by using ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found