Given 2 combobox, how to select an option from a select list with React Testing Library

Viewed 837

So i'm following this example How to select an option from a select list with React Testing Library

Now in my case i have 2 dropdown lists,

<select data-testid="select state">
  <option>
    CA
  </option>
  <option>
    NY 
  </option>
  <option>
    MA
  </option>
</select>

<select data-testid="select city">
  <option>
    New York
  </option>
  <option>
    San Diego
  </option>
</select>

Assuming i only have the 1st dropdown, the test can be like this to choose 'MA'

it('should correctly set default option', () => {
  render(<App />)
  expect(screen.getByRole('option', {name: 'CA'}).selected).toBe(true)
})


it('should allow ...', () => {
  render(<App />)
  userEvent.selectOptions(
    // Find the select element
    screen.getByRole('combobox'),
    // Find and select the Ireland option
    screen.getByRole('option', {name: 'MA'}),
  )
  expect(screen.getByRole('option', {name: 'MA'}).selected).toBe(true)
})

Q1: if i turn on the 2nd dropdown list, the unit test reports: Found multiple elements with the role "combobox" How should i update the test pls ?

Q2: i tried to replace

screen.getByRole('combobox')

with

screen.getByTest('select state')

The original sample test will fail, it cannot see the other options other than the 1st default option.

Any suggestions pls ?

1 Answers

My bad, there's a space in the option names 'MA '. i removed the space and things start working

Related