6

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.

Layup
  • 81
  • 1
  • 2

1 Answers1

3

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});
Mo.
  • 26,306
  • 36
  • 159
  • 225
4T2
  • 31
  • 2
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 02 '22 at 14:21
  • This fixed the issue for me. Interesting note: Even though I was using 'substring match' like this: `getByLabelText(/My text/i)`, the test didn't pass. I could see my string in the DOM too. – ndogac May 19 '23 at 13:46