使用测试 ID 获取元素后,是否可以检查它所在的 html 标签名称?

Is it possible to check the html tag name on which it is present after getting the element using test id?

假设我的 component.tsx 文件中有这段代码。是否可以检查存在特定测试 ID 的标签名称?

<section>
  <h1 data-testid="page-header">
    Welcome!
  </h1>
  <Link data-testid="about-page-link" to="/about">
    Go to about
  </Link>
</section>

我有以下代码通过我的测试文件中的测试 ID 获取元素。

const headerElement = screen.getByTestId('page-header');

是否可以检查 h1 标签上是否存在以下标签?

简而言之,我需要检查 page-header 测试 ID 是否出现在 h1 标签上

是的,你可以得到单个 HTML h1 元素 data-testid as

const element = document.querySelector("h1[data-testid]")
if (element && element.dataset.testid === "page-header") {
  console.log("Yeah it is present");
} else {
  console.log("Nope it's not there");
}
<section>
  <h1 data-testid="page-header">
    Welcome!
  </h1>
  <Link data-testid="about-page-link" to="/about"> Go to about
  </Link>
</section>

你可以获取所有h1个标题并获取它们的data-testid属性然后匹配它

const allHeading = [...document.querySelectorAll("h1")]
const idToSearch = "page-header";

const result = allHeading.some(heading => {
  const testId = heading.dataset.testid;
  return testId === idToSearch;
})
console.log(result);
<section>
  <h1 data-testid="page-header">
    Welcome!
  </h1>
  <Link data-testid="about-page-link" to="/about"> Go to about
  </Link>
</section>

可以直接通过data属性查询,查看返回的NodeList长度

document.querySelectorAll("h1[data-testid='page-header']");

// or if you just want the first/only H1 with the relevant attribute
document.querySelector("h1[data-testid='page-header']");

const idToSearch = 'page-header';
const testIds = document.querySelectorAll(`h1[data-testid='${idToSearch}']`)

console.log(!!testIds.length);
<section>
  <h1 data-testid="page-header">
    Welcome!
  </h1>
  <Link data-testid="about-page-link" to="/about"> Go to about
  </Link>
</section>