getByRole 查询段落在 React 测试期间不起作用

getByRole query for paragraph not working during React testing

我创建了一个简单的计数器应用程序来学习 react testing library。但是当我测试是否使用 {count} 文本呈现段落时,我卡住了。

Main.jsx

function Main() {
  const [Count, setCount] = useState(0);

  function handleCount() {
    setCount((c) => c + 1);
  }
  return (
    <div>
      <h1>Counter App</h1>
      <Counter count={Count} />
      <Button label="Click me" handleCount={handleCount} />
    </div>
  );
}

Counter.jsx

function Counter({ count }) {
  return <p>{count}</p>;
}

Main.spec.jsx

it("should render count", () => {
    render(<Main />);
    expect(screen.getByRole("paragraph")).toBeInTheDocument();
});

此测试不足以通过。我知道我们可以将 data-testid 添加到 <p> DOM 节点,然后我们可以通过 getByTestId 查询来测试它。但我想知道为什么我上面使用 getByRole('paragraph') 的测试用例每次都失败。

getByRole利用不同元素的HTML作用。段落不是有效角色,这就是您的查询不起作用的原因。您可以在此处阅读有关 getByRole https://testing-library.com/docs/dom-testing-library/api-queries/#byrole and about the different roles in html here: https://www.w3.org/TR/html-aria/#docconformance.

的更多信息

例如,您可以使用 getByText 来实现您想要的(在此处阅读有关首选查询的更多信息:https://testing-library.com/docs/guide-which-query/)。

expect(screen.getByText("0")).toBeInTheDocument();