Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the element with the testid using react testing library?

Hi i want to access the first div with class "icon" using getByTestId.

below is how the DOM looks,

<div class="parent">
    <div data-testid="add">
        <div class="info"></div> 
        <div class="action">
            <div class="icon"/> //want to access this 
        </div>
    </div>
</div>
<div class="parent">
    <div data-testid="add">
        <div class="info"></div> 
        <div class="action">
            <div class="icon"/> 
        </div>
    </div>
</div>

As you see from above there are multiple elements with testid "add" how can i get the first add div and access its child div with class icon.

i have tried

const element  = queryAllByTestId('add')[0].querySelector(
    'div'
  )[1];

this gives element undefined.

could someone help me with this. thanks.

like image 200
someuser2491 Avatar asked May 15 '20 04:05

someuser2491


1 Answers

getAllBy

getAllBy* queries return an array of all matching nodes for a query, and throw an error if no elements match.

queryAllBy

queryAllBy* queries return an array of all matching nodes for a query, and return an empty array ([]) if no elements match.

Query Cheetsheet

enter image description here

Use the query variant so as not to throw in a test if no matches found, and use querySelectorAll since querySelector returns only the first element that matches, or null.

const element = queryAllByTestId("add");
if (element.length) {
  let divs = element[0].querySelectorAll("div");
  // ...get the div node you need
}

You can even specify divs with a specific class

const element = queryAllByTestId("add");
if (element.length) {
  let divs = element[0].querySelectorAll("div.icon");
  // ...get the div node you need
}
like image 52
Drew Reese Avatar answered Sep 21 '22 18:09

Drew Reese