1

This is the structure of the HTML rendered by React. I cant pass any test id to select and option tags, but i can define a test id for the wrapper. Please see below code

    <div data-testid="select">
  <labe>Select a country</labe>
  <div>
    <select>
      <option>USA</option>
      <option>UK</option>
    </select>
  </div>
</div>

i tried to to get select and option using

screen.getByTestId("select")

but it is not working, i want onChange event to test for this dropdown, how can access options of select in case of custom select

1 Answer 1

1

First of all, heads up: you have <labe>Select a country</labe> which should be <label>Select a country</label>.

Secondly-- there are a few ways to do this, and the test id isn't actually necessary, if you want to avoid it.

Option #1- Using a test ID and within:

const selectWrapper = screen.getByTestId("select");
const actualSelect = within(selectWrapper).getByRole('combobox');

(I think the role here is 'combobox', but it might be 'select'; you'd have to experiment).

Option #2- Using proper accessible querying:

You can also filter by accessible name with getByRole or use getByLabelText-- if you have properly wired a relationship between the label and the control (usually by wrapping the control in the label or using the for attribute on the <label/>. So for instance if your markup was rewritten as:

<div data-testid="select">
  <label>
    Select a country
    <div>
      <select id="country" name="country">
        <option>USA</option>
        <option>UK</option>
      </select>
    </div>
  </label>
</div>

Then you could omit the test id entirely and simply use:

const countrySelect = screen.getByLabelText(/Select a country/);

Please note this quote from the docs regarding getByTestId:

The user cannot see (or hear) these, so this is only recommended for cases where you can't match by role or text or it doesn't make sense (e.g. the text is dynamic).

One of the greatest strengths of React Testing Library is that, if you use the recommended, accessibility-minded selection, you get some degree of accessibility testing for free. If you are leaning heavily on getByTestId that should be a code smell for you that you may not building your pages in an accessible way, which could cost you money in lost sales to users leveraging assistive technologies, or even a lawsuit in some cases.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.