Search code examples
react-testing-library

How to select an option from a select list with React Testing Library


I have a normal select list. I need to test handleChoice gets called when I choose an option. How can I do this with React Testing Library?

  <select
    onChange={handleChoice}
    data-testid="select"
  >
    <option value="default">Make your choice</option>
    {attributes.map(item => {
      return (
        <option key={item.key} value={item.key}>
          {item.label}
        </option>
      );
    })}
  </select>

getByDisplayValue with the value of item.label doesn't return anything, perhaps this is because it's not visible on the page?


Solution

  • Add data-testid to the options

      <option data-testid="select-option" key={item.key} value={item.key}>
          {item.label}
      </option>
    

    Then, in the test call fireEvent.change, get all the options by getAllByTestId and check the selected option:

    import React from 'react';
    import { render, fireEvent } from '@testing-library/react';
    import App from './App';
    
    test('Simulates selection', () => {
      const { getByTestId, getAllByTestId } = render(<App />);
      //The value should be the key of the option
      fireEvent.change(getByTestId('select'), { target: { value: 2 } })
      let options = getAllByTestId('select-option')
      expect(options[0].selected).toBeFalsy();
      expect(options[1].selected).toBeTruthy();
      expect(options[2].selected).toBeFalsy();
      //...
    })
    

    For your question, the getByDisplayValue works only on displayed values