1. 4
    Use the findBy Query to get Elements that Will Show up on the Page
    1m 25s

Use the findBy Query to get Elements that Will Show up on the Page

Daniel Afonso
InstructorDaniel Afonso
Share this video with your friends

Social Share Links

Send Tweet

In order for you to interact with the elements in your tests, you need to query for them. Well, sometimes, they take time to show up in your UI.

In this lesson, we will learn about one of the query variants that allows you to search for something that you expect to show up eventually in your UI: the findBy*.

Instructor: [0:00] There are going to be scenarios that something won't immediately show up in your UI. This can be a consequence of, for instance, a data fetching request.

[0:08] By leveraging useState, useEffect and setTimeout, let us add some text to our UI that will only render after 500 milliseconds. If we replicate the same test we did for the getBy scenario and replace our string for the one that we expect to show up and run our test, it will fail.

[0:25] This is because both queryBy and getBy queries are synchronous. This means that the moment they run, they expect immediately for a result. In this scenario that we know that something will show up in our UI, but it won't be there at the exact moment we run our query, we need something to wait for.

[0:42] We need something asynchronous. For these specific cases, we can leverage the findBy query. The findBy query returns a promise that will resolve when it finds what it's looking for, and rejects when it doesn't. Let us change this test to work with findBy.

[0:58] First, since we'll be waiting for a promise, our test needs to be asynchronous. Let's add async. Secondly, we destructure the findByText query from render. Finally, we replace our getByText with findBy and wait for it.

[1:13] Now, if we run our test, we should see that because of the findBy query, our test waits until the string, this test, will show up, appears, and only then, when that happens, does the assertion.