React Testing Library unable to find text even though screen.debug() shows the text to exist
Asked Answered
S

1

11

In a nutshell, if I grab a portion of the screen by it's label:

const foo = screen.getByLabelText('Some Label');

I can see that the element I'm interested in exists in the output:

debug(foo);
...
<div
  class=" css-15zcpdi-NoOptionsMessage"
>
   Something went wrong
</div>

However if I search for "Something went wrong" in the screen:

screen.getByText('Something went wrong');

RTL claims it can't find it:

TestingLibraryElementError: Unable to find an element with the text: Something went wrong. ...

I must be doing something wrong here.. What?

Stadia answered 5/6, 2020 at 22:50 Comment(3)
Is there any async rendering in your component ? Can you post test code ?Liberec
Did you figure out what went wrong? I'm having a similar problemRms
Do you have a true minimal reproducible example for folks to look at? (And don't underestimate the power of an MCVE: it forces your to reduce your code to the bare minimum, so you almost always find the problem yourself just by trying to form one). And if you do: did you file an issue with Jest over on github.com/facebook/jest/issues? Because if you can cleanly reproduce this, that's almost certainly something the Jest team will want to know about.Riyal
G
10

Using exact string values does not seem to work very consistently. Try a regular expression instead:

screen.getByText(/Something went wrong/);
Grunter answered 2/11, 2021 at 22:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.