Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-testing-library getAll and then filter to find an element

I have a page which renders a list of custom checkboxes. Each checkbox looks like this.

<div
  className="checkbox"
  role="checkbox"
  onClick={onClick}
  onKeyPress={onKeyPress}
  aria-checked={getState().checked}
  tabIndex={0}
>
  {getState().checked ? (
    <span className="checkbox__icon checkbox__selected">
      <Icon src="/icons/check-box-selected.svg" alt="checkbox selected" />
    </span>
  ) : (
    <span className="checkbox__icon">
      <Icon src="/icons/check-box-empty.svg" alt="checkbox not selected" />
    </span>
  )}
  <span className="checkbox__label">{label}</span>
</div>

I would like to be able to find a particular checkbox while testing. The checkboxes differ in their labels (currently implemented using span and key/click handlers).

I want to test when the label is clicked, the image should change.

Let's say user clicked on checkbox1 with label "checkbox1", the image should change from "checkbox selected" to "checkbox not selected"

I am facing issues while trying to get reference to a checkbox with a particular label.

If i do getByText("checkbox1") , it returns me the span element, and I don't have a reference to the actual checkbox to assert whether the image has changed.

My workaround for now is to getAllByRole and then filter(item => item.textContext === "checkbox1") and then queryByAltText.

Is there a better approach to test this?

like image 992
gaurav5430 Avatar asked Jan 26 '26 05:01

gaurav5430


1 Answers

Well, the best way, in my opinion, will be to give the checkbox div an id prop with the label var and just do getElementByID.

But if you get the span like you say you can always do .parentElement and get the checkbox div.

You can also use .closest("div.checkbox"); on the span and it will look for the closest div with class checkbox.

like image 60
MennyMez Avatar answered Jan 28 '26 20:01

MennyMez