小编Ale*_* G.的帖子

React 测试库 getByRole('heading') 如何获取具有特定标题级别的节点

我有一个 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 …
Run Code Online (Sandbox Code Playgroud)

react-testing-library

14
推荐指数
1
解决办法
2万
查看次数

标签 统计

react-testing-library ×1