Ale*_* G. 14 react-testing-library
我有一个 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 }));
});Run Code Online (Sandbox Code Playgroud)
这是错误:
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>Run Code Online (Sandbox Code Playgroud)
解决了。
原因是库的版本。默认情况下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
Run Code Online (Sandbox Code Playgroud)
要更新依赖项,请打开package.json并手动将它们更新到最新版本:
...
"dependencies": {
...
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.0.2",
"@testing-library/user-event": "^12.1.4"
...
},
...
Run Code Online (Sandbox Code Playgroud)
保存更改并运行 CLI 命令:npm install
| 归档时间: |
|
| 查看次数: |
18089 次 |
| 最近记录: |