1. 14
    Constrain a Query to a Specific Element Using Within
    1m 2s

Constrain a Query to a Specific Element Using Within

Daniel Afonso
InstructorDaniel Afonso
Share this video with your friends

Social Share Links

Send Tweet

Given how web pages are built nowadays, you might find yourself with multiple instances of the same element.

To avoid querying for a list of elements and then filtering them down, you can constrain your query to a specific area.

In this lesson, we are going to learn how to leverage the within helper to constrain our query to a specific element.

Instructor: [0:00] Sometimes, you might want to query inside a specific part of your UI. This is a great scenario to leverage the within helper. Looking at our code, here we have a div with a test ID child container. Inside this div, we have a button with a text, show hidden text. In a normal scenario, we could just query directly for this button.

[0:19] Now, imagine that this button ends up being duplicated. We would either have to leverage the getAllBy query, or either constrain our query to this div. Because we will use the within helper, let us constrain our query. In our test case, let's first render our component and getOurChildContainer by using the byTestID query.

[0:38] Now that we have our div, let's import within from the testing library. Using within, let's pass it our div and run a getByRole query to get a button with a show hidden text name. What this will do is constrain this getByRole query to this given div. Now, let us assert that our button is in the document. If we run our test, you should see that it has passed.