jest-dom: getRootNode not returning Document for element matched with findByText query

  • @testing-library/jest-dom version: 5.14.1
  • node version: 14.17.1
  • yarn version: 1.22.10
  • dom-testing-library version: 8.1.0
  • @testing-library/react version: 12.0.0

Relevant code or config:

// [1] Sporadically fails
expect(await screen.findByText('hello')).toBeInTheDocument();

// vs.

// [2] Passes every time without fail
waitFor(() => {
  expect(screen.getByText('hello')).toBeInTheDocument();
})

What you did:

Used expectation pattern [1] over [2]

What happened:

Sporadic failures Received element is not visible (element is not in the document)

Problem description:

Essentially this check fails: https://github.com/testing-library/jest-dom/blob/main/src/to-be-in-the-document.js#L11 because sporadically getRootNode returns the React node that got matched itself rather than the Document.

Which means that findBy... succeeds in returning a matched node, however when verifying if this node is in the Document with .toBeInTheDocument() it fails.

Suggested solution:

I don’t know enough about the internals of when the root node changes from the React node to the Document node. I know for sure the root node eventually changes to Document, hence why the waitFor [2] pattern works.

Reproducing is difficult because of it’s sporadic nature, but I’m essentially creating this issue to find out if others are being affected by this, and also to learn a bit more about the internals that could be resulting in this issue.

In the meantime I’ll be using the waitFor[2] expectation pattern from now, but I’m worried that I may forget about this issue and have sporadic failures again in the future since pattern [1] is the first that comes to mind.

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 6
  • Comments: 15 (2 by maintainers)

Most upvoted comments

Hi, I also faced this problem and got some small reproducible patterns, and some memorization solve them.

working sample: https://codesandbox.io/s/jest-dom-404-repro-mmb2s

implementation is also folded here
import { useEffect, useReducer, useState } from "react";

export function Container({ Inner }) {
  const [visible, setVisible] = useState(false);
  const [, rerender] = useReducer((x) => !x);

  useEffect(() => {
    if (!visible) {
      // this MUST use task queue. sync OR microtask cannot repro(in my test
      setTimeout(() => {
        setVisible(true);
      }, 100);
    }
  }, [visible]);

  useEffect(() => {
    if (visible) {
      rerender();
    }
  }, [visible]);

  return <div>{visible && <Inner />}</div>;
}

// <Container Inner={InstantComponent} />
export function InstantComponent() {
  // FaCC or HoC easily falls into this situation

  // memorize this
  const TmpComp = (props) => <span {...props} />;

  return (
    <div>
      <TmpComp>foo</TmpComp>
    </div>
  );
}

// <Container Inner={KeyedComponent} />
export function KeyedComponent() {
  // memorize this
  const key = Date.now().toFixed() + "$" + (Math.random() * 10000).toFixed();
  return (
    <div>
      <span key={key}>foo</span>
    </div>
  );
}

It seems that the element~s~ of the first result are detached from the tree. Are you in the same situation?

I did another research for previous comment. I’ve found that the detached element is easy to get and hard to notice.

Here is my latest research. https://codesandbox.io/s/peaceful-thunder-h7tfmx

This mini-app says two points:

  1. Switching between React components generates different elements. Even if the final DOM structure is consistent.
  2. When the parent React component switches, the child components generate different elements. Even if children rendered by the same component.

And we already know that components declared in render cause component switching.

So the following patterns are suspicious:

1. Inline component: Components declared in render function

function Inline() {
  const Needle = () => <span>needle</span>;
  return (
    <div>
      <Needle />
    </div>
  );
}

Real world example: Row renderer of table-like component

full code(codesandbox)

const SEED = [1, 2, 3];
const USER = 2;

export function App() {
  const seed = SEED; // given table values
  const user = useAsyncValue(USER); // something like `fetch("/user")`
  const rowRenderer = useCallback(
    function Row({ id }: { id: number }) {
      return (
        <span>
          id: {id}
          {id === 2 && ", needle"}
          {id === user && ", me"}
        </span>
      );
    },
    [user]
  );

  return (
    <div>{seed ? seed.map((x) => rowRenderer({ id: x })) : "(empty)"}</div>
  );
  // `x => <rowRenderer id={x} / >` will achieve same result
}

If you like, change the version on the Dependencies tab and check it out.

It would be nice to be able to extract the variables in the parent scope, reference them using props, and move the component to the top level.

2. Shared component: Components shared by two or many parent component

function Needle() {
  return <span>needle</span>;
}
function A() {
  return <div><Needle /></span>
}
function B() {
  return <div><Needle /></span>
}
function App() {
  return <div>{Math.random() < 0.5 ? <A/> : <B/>}</div>
}

This pattern also cause detached elements. Real world example is not ready, but a SPA router could belong to this pattern.

After updating our dependencies the problem we were experiencing disappeared.

because sporadically getRootNode returns the React node that got matched itself rather than the Document

Hmmm, this seems to be the key of the issue. However, we do not control getRootNode. It’s from jsdom. I wonder if either jsdom or the way findByText works has something to do with this. I do not see much that we can do from jest-dom’s perspective.

I tried this for now: I forked the codesandbox example provided by @berlysia above (see https://github.com/testing-library/jest-dom/issues/404#issuecomment-952179213). Then I focused on one of the failing tests alone, and modified it in this way:

  test.only('findBy', async () => {
    const { debug } = setup() // modified setup to return render too
    const element = await screen.findByText('foo')
    debug()
    console.log('root node', element.getRootNode())
    console.log('parent', element.parentElement)
    expect(element).toBeInTheDocument()
  })

This is the output I get in the console:

image

Not sure what to make of it. The element appears placed correctly in the DOM tree, but for some reason its parentElement is null, and calling its getRootElement() returns the element itself, instead of the document where it lives.

I’m honestly not sure right now how .toBeInTheDocument’s implementation is at fault here. Suggestions are welcome.