When working with React, I have a scenario where I am mapping out elements from an array. For instance:
{options.map((option)=>{
return <div data-testid="option">{option}</div>
})
In some cases, I need to select an option without knowing its exact text content. In such situations, I use data-testid="option"
as an identifier and select the first option with
screenGetAllByTestId('option')[0]
...
However, there are instances where I know the specific option I want and would like to use getByTestId
, but it becomes challenging as all options share the same data-testid.
My goal is to achieve something akin to the following pseudo code:
screen.getAllByTestId('option').getByText("Apples")
This code snippet is designed to fetch all options and then pinpoint the one that contains the text "Apples".