1. 2
    Use the getBy Query to get Elements that Should Always be on the Page
    1m 45s

Use the getBy Query to get Elements that Should Always be 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.

In this lesson, we will learn about one of the query variants that allows you to search for something that you expect to always be in your UI: the getBy.

We will also get introduced to one of the most useful jest-dom assertions: the toBeInTheDocument.

Instructor: [0:04] The most important thing a render returns is something I haven't showed you yet, and that is queries. Queries are the methods offered by the testing library that allow you to find for elements on the page. There are three types of queries and each query can be customized through an accessibility prioritization.

[0:20] In these and the two lessons after, we are going to focus on the types of queries. Picture you want to find something that will always exist on your UI. Looking at our page for this scenario, we'll use this header here that says this is an Edge1.

[0:30] In scenarios like this where we know that something will be on the UI, when we try to query for it, we should use the getBy variant. The syntax on how to do this is to write getBy and then customize the query what we want to look for.

[0:47] In this case, we want to look for our text. Let's use the getBy text query. In order to do so, we must pass to our getBy text query, the text we will be looking for, which in this scenario is going to be, "This is an Edge1." Once our query runs, it should find our header and assign it to this header const here.

[1:03] This is how you can query for stuff using the getBy query. To make sure our test is complete, let us add an assertion to make sure the query worked. For this, we'll leverage the [indecipherable] toBeInTheDocument to assert if the header we just queried for is in our UI. If we run our test, we should see that it has passed.

[1:24] One peculiarity about the getBy queries is its behavior when it does not find what it's looking for. If inside our app component we comment our Edge1 and let our test rerun, we should see that now the getBy text threw an error.

[1:35] This is because getBy queries will either return the result of the query when they find it, or in the case they don't, they throw an error. To wrap up, let's uncomment our Edge1 and let our test pass.