How to write unit test for custom select in React with out test id defined for select or option tag

Viewed 301

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 Answers

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.

Related