You can think of waitFor as a way to delay your test until some arbitrary criteria is met. findBy on the other hand is a much more specific tool. Wait until this query resolves. The docs recommend using this tool for cases where you interact with the UI but need to wait a little bit before the changes show up on the page. Like waitFor
it checks immediately and then after 50ms
up until a 1000ms
timeout, which is totally customizable.
The way we're using it here really isn't that optimal because it's generally going to slower than a getBy
query. When I ran some tests the first query took around 70ms
while the rest all took around 50ms
. It might even have been better to explicitly findBy
the first heading and then getBy
all of the rest or even findByAll
and then compare them that way.
Checkout the About Queries section of the Testing Library docs that covers the differences between getBy
, findBy
and queryBy
. Another section called Async Methods covers all of the details around waitFor
and findBy
.
Instructor: Go ahead and start Jest up in watch mode, with a filter on Products.Test. Now in products.test.tsx, add a new test called Each Individual Product Should Contain A Heading. That will also take an async function.
Inside of that test, let's go ahead and renderWithContext, products. Then, below that, type for let product of myProducts, and then inside of that, await Screen.findByRole, the Role will be Heading. Then let's pass in an Options object, name of Product.Name. Go ahead and save that. You can see that it passed.
Now, this is interesting, because we already knew from before that immediately after renderWithContext, that after Products is rendered, it doesn't actually have any products. In fact, if we do const debug = renderWithContext, and execute debug here, you'll see that we don't have any products.
What's happening is, when we call findByRole instead of getByRole, findByRole with await actually waits until the heading is found. I don't know, it waits a certain number of seconds before it will time out.
It gives you that time, so we don't need to expressly call await before we can just say, "Wait until you find a heading that matches, and when you do, continue on with your test."
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!