testing-library / dom-testing-library

🐙 Simple and complete DOM testing utilities that encourage good testing practices.
https://testing-library.com/dom
MIT License
3.26k stars 466 forks source link

getByRole with name fails if there's disabled style defined: "Cannot read properties of null (reading 'parentElement')" #1190

Closed JuhG closed 5 months ago

JuhG commented 1 year ago

Relevant code or config:

screen.getByRole("checkbox", { name: "testLabel" });
<div>
  <input type="checkbox" id="testName" />
  <label htmlFor="testName">
    <svg viewBox="0 0 12 10">
      <polyline points="1.5 6 4.5 9 10.5 1" />
    </svg>
    <span>testLabel</span>
  </label>
</div>
input:disabled + label svg {
  background: red;
}

What you did:

I was testing a checkbox component and sometimes I got this error. Tried to narrow the issue down, this is how far I got.

What happened:

I get this error:

Cannot read properties of null (reading 'parentElement')

Screen Shot 2022-11-23 at 13 15 55

Reproduction:

https://codesandbox.io/s/vibrant-tess-9mvjex?file=/src/App.test.tsx

Problem description:

Not sure what exactly causing this, but all these things are needed for me to reproduce:

If you move the label inside or remove the disabled style, the error goes away. If I should open an issue in another repo, please let me know. Thanks!

cvharris commented 1 year ago

This is a really strange bug and plagued me as well, I solved it by using aria-labelledby and switching to getByLabelText. The other solutions—remove :disabled styles or nest <input /> inside <label>—didn't apply well to our particular use case

cmorten commented 5 months ago

Potential duplicate / related to https://github.com/testing-library/dom-testing-library/issues/1101?

eps1lon commented 5 months ago

Closing in favor of https://github.com/testing-library/dom-testing-library/issues/1101