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
Published 6 months ago
Updated 5 months ago

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.

egghead
egghead
~ an hour ago

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

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

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!

Markdown supported.
Become a member to join the discussionEnroll Today