Sub*_*aik 19 reactjs react-testing-library
我创建了一个简单的计数器应用程序用于学习react testing library
。但是当我测试段落是否用{count}
文本呈现时,我陷入了困境。
主.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>
);
}
Run Code Online (Sandbox Code Playgroud)
计数器.jsx
function Counter({ count }) {
return <p>{count}</p>;
}
Run Code Online (Sandbox Code Playgroud)
主要规范.jsx
it("should render count", () => {
render(<Main />);
expect(screen.getByRole("paragraph")).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
这个测试还不足以通过。我知道我们可以添加data-testid
到<p>
DOM 节点,然后我们可以通过getByTestId
查询来测试它。但我想知道为什么我上面使用的测试用例getByRole('paragraph')
每次都会失败。
The*_*ool 19
getByRole
使用不同元素的 HTML 角色。段落不是有效的角色,这就是您的查询不起作用的原因。您可以在这里阅读有关getByRole
https://testing-library.com/docs/dom-testing-library/api-queries/#byrole以及 html 中不同角色的更多信息: https: //www.w3.org/TR /html-aria/#docconformance。
例如,您可以使用getByText
相反 来实现您想要的(在此处阅读有关首选查询的更多信息: https: //testing-library.com/docs/guide-which-query/)。
expect(screen.getByText("0")).toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)