What could cause getByLabelText
from testing-library to report that it can't find an element when the element is definitely there? The exact error I'm getting is
TestingLibraryElementError: Unable to find a label with the text of: Remove Item: Item C
It appeared after I ran a test that reported failure on the line
const removeItemButton = screen.getByLabelText('Remove Item: Item C');
The test output contained a chunk of page source that included
<span
class="my-company-span"
data-testid="custom-react-tag"
>
Item: Item C
<button
aria-label="Remove Item: Item C"
class="myco-chp__button"
type="button"
>
...
For further proof that the element does exist, I ended up getting it using a different function (getAllByRole
) but I think getByLabelText
would be cleaner.
The documentation says that aria-label
attributes are valid targets for getByLabelText
. Just in case there was an unusual character in there, I copy-pasted the name of the aria-label
directly from the error output to the getByLabelText
argument, and nothing changed. I am using the function getByLabelText()
successfully on other elements in the same file, so it's not a bad import.
I've seen a lot of questions online for the similar-but-not-the-same error "Unable to find an element with the text" but the only thing I found for my situation was for someone using iframes, which doesn't apply to me.