0

假设我的 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上是否存在测试 IDh1

4

2 回答 2

2

是的,您可以使用as获取单个 HTMLh1元素data-testid

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>

于 2021-06-27T13:41:01.183 回答
0

You can query by data attribute directly and check the length of the returned 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>

于 2021-06-27T13:49:48.520 回答