如何允许 screen.getByText() 在 jest + react 测试中失败

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

我有一个测试用例。该项目正在使用 @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();
  });

它不允许我 运行 行 expect(loaderElementText).not.toBeInTheDocument(); 并出现以下错误:

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.

反向测试用例,loading={true} 按预期工作。

我已经无计可施了。查询文档中的元素并期望找不到该元素的语法是什么?

为那些好奇的人发布答案:使用 screen.queryByText(),失败时 returns null 而不是抛出运行时错误。