1. 5
    Use the AllBy variant to get Multiple Instances of an Element
    1m 9s

Use the AllBy variant to get Multiple Instances of an Element

Daniel Afonso
InstructorDaniel Afonso
Share this video with your friends

Social Share Links

Send Tweet

Sometimes you may need to get more than just one result from your queries.

In this lesson, you are going to learn how you can leverage the AllBy variant to extend your queries to find an array of elements instead of a single one.

Instructor: [0:00] All the queries we saw in the last three lessons only returned the first matching node. This means that if we have multiple instances of a single node, these queries will fail. In order to understand this, in our UI, let's copy and paste our Edge1 multiple times.

[0:15] In this case, we know that there are five instances of, "This is an Edge1 in our component." Back to our test, let's leverage the code of the getByTest and paste it here.

[0:25] As you can see, if we run our test, the test has failed with an error message of, "Found multiple elements with the text. This is an Edge1." In scenarios we want to look for multiple instances of the same element, we can add the word "all" in our queries.

[0:39] This means that we would end up with queryAllBy, getAllBy, and findAllBy. Let us now refactor our test to apply this. First, we destructure the getAllByText query from Render.

[0:50] Then, we use it to get all the this is an Edge1 text instances in our UI. Since the toBeInTheDocument assertion expects a single element, let's change our assertion as well to instead expect that our headers list array has a length of five. Finally, if we rerun our test, you should see that it has passed.