如何解决React Testing Library getByRole'heading'如何获取具有特定标题级别的节点
我有一个h1标记,我正在尝试使用特定的标题级别获取节点,但遇到错误:
找到了多个具有“标题”角色的元素
根据documentation此查询应该仅返回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>
解决方法
您使用的是哪个“ @ testing-library / react”版本?尝试更新它,因为您的代码可以在“ @ testing-library / react”:“ ^ 10.4.9”上正常工作
,已解决。
原因是库的版本。默认情况下,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。