Reputation: 101
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.
Upvotes: 8
Views: 11222
Reputation: 151
I changed from getByLabelText to the more recommended getByRole, and that solved the issue. In your case, that would be
screen.getByRole<HTMLButtonElement>('button', { name: 'Remove Item: Item C' })
Upvotes: 0
Reputation: 71
Not sure if this is what is happening here, but I ran into a similar problem testing Material UI Textfields. What I finally end up doing was passing in the exact parameter as false. It's not evident looking at the output what extra characters might be getting added.
For your query it would look like this:
const removeItemButton = screen.getByLabelText('Remove Item: Item C', {exact:false});
Upvotes: 7