我有一个h1标记,我试图使用特定的标题级别获取节点,但运行时出现错误:
找到多个具有角色"的元素;标题";
根据文档,该查询应该只返回h1。
这是一个例子:
import React from "react";
import { render, screen } from "@testing-library/react";
it("Should found only header1", async () => {
render(
<div>
<h1>editable content</h1>
<p>and</p>
<h2>other header</h2>
</div>
);
screen.debug(screen.getByRole("heading", { level: 1 }));
});
这是一个错误:
Found multiple elements with the role "heading"
(If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).
<body>
<div>
<div>
<h1>
editable content
</h1>
<p>
and
</p>
<h2>
other header
</h2>
</div>
</div>
</body>
已解决
原因是库的版本。默认情况下,create-react-app
安装@testing-library
的过期版本
运行CLI命令npm outdated
并检查依赖项的版本:
Package Current Wanted Latest
@testing-library/jest-dom 4.2.4 4.2.4 5.11.4
@testing-library/react 9.5.0 9.5.0 11.0.2
@testing-library/user-event 7.2.1 7.2.1 12.1.4
要更新依赖项,请打开package.json
并手动将其更新为最新版本:
...
"dependencies": {
...
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.0.2",
"@testing-library/user-event": "^12.1.4"
...
},
...
保存更改并运行CLI命令:npm install