0

Suppose I have this code in my component.tsx file. Is there a possibility to check the tag name on which a paricular test id is present ?

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

I have the following code to get the element by test id in my test file.

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

Is it possible to check if the following tag is present on an h1 tag ?

in short i need to check whether page-header test id is present on h1 tag

Franklin Pious
  • 3,670
  • 3
  • 26
  • 30

2 Answers2

2

Yeah you can get the single HTML h1 element with 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>

You can get all h1 headings and get their data-testid attribute and then match it

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>
DecPK
  • 24,537
  • 6
  • 26
  • 42
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>
pilchard
  • 12,414
  • 5
  • 11
  • 23