Search code examples
javascriptreactjstestingreact-testing-librarytesting-library

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


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


Solution

  • 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>