admin管理员组

文章数量:1289557

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?

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?

Share Improve this question asked Jul 7, 2021 at 17:14 Our_BenefactorsOur_Benefactors 3,5393 gold badges23 silver badges29 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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

本文标签: javascriptHow to allow screengetByText() to fail in jestreact testStack Overflow