Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow screen.getByText() to fail in jest + react test

I have a testcase. This project is using @testing-library/react

it('renders content if loading is false', async () => {
    await waitFor(() => {
      render(<Loader loading={false}><span>foo</span></Loader>);
    });
    const loaderElementText = screen.getByText('Loading');
    expect(loaderElementText).not.toBeInTheDocument();
    const contentText = screen.getByText('foo');
    expect(contentText).toBeInTheDocument();
  });

It does not allow me to run the line expect(loaderElementText).not.toBeInTheDocument(); with the following error:

TestingLibraryElementError: Unable to find an element with the text: Loading. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

The inverse testcase, with loading={true} works as expected.

I'm at my wits end. What is the syntax to query the document for an element, and expect that the element is not found?

like image 530
Our_Benefactors Avatar asked Sep 12 '25 01:09

Our_Benefactors


1 Answers

Posting the answer for those curious: use screen.queryByText(), which returns null on failure instead of throwing a runtime error.

like image 193
Our_Benefactors Avatar answered Sep 13 '25 15:09

Our_Benefactors