testing-library / dom-testing-library

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

Having a <p> inside a <label> breaks the query #1280

Closed oncet closed 11 months ago

oncet commented 11 months ago

Relevant code or config:

<label>
  Foo
  <input />
  <p>Bar</p>
</label>
screen.getByLabelText('Foo')

What you did:

Trying to select a label with the text Foo.

What happened:

TestingLibraryElementError: Unable to find a label with the text of: Foo

Reproduction:

https://testing-playground.com/gist/e1e06f483627136ea87dc1435240f511/f11bc0299718a098e86958de617642a8fe6f1447

Problem description:

My <label> contains an <input> and a <p> for displaying errors and I can't selected using the recommended query for form inputs.

Suggested solution:

Allow selecting by label text even if it has a nested paragraph.

oncet commented 11 months ago

After some thought, I think the problem is not related to specifically to <p>, it could be any other element. The actual problem seems that all text nodes inside a <label> are considered part of the label text.

For example, using this selector works:

screen.getByLabelText('Foo Bar')
oncet commented 11 months ago

Just realized I could also use a regular expression instead of a string:

screen.getByLabelText(/Foo/)