Select box test in react tesing library

I have a select box, and i want to create a test for it, by choosing the 2nd option in the list. but i got this error

Error: TestingLibraryElementError: Value "Female" not found in options

   <input name="gender" role="combobox">
      <button class="combobox-arrow"></button>
      <ul role="listbox">
       <li
        role="option"
        value="Male"
       ><span>Male</span></li>
       <li
        role="option"
        value="Female"
       ><span>Female</span></li>
      </ul>
const inputElement = screen.getByRole("combobox", {
    name: /gender/i,
  });
 userEvent.selectOptions(inputElement, "Female");

>Solution :

The issue with your test is that you are using userEvent.selectOptions() method to select an option from the combobox, but the combobox in your code is not an HTML element. Instead, it is a custom dropdown menu that uses an unordered list with role="listbox" and role="option" to display its options.

To select an option from the custom dropdown menu, you can use userEvent.click() to open the dropdown menu and then screen.getByRole() to find the option element with role="option" and value="Female". Here’s how you can modify your test to select the "Female" option:


const inputElement = screen.getByRole("combobox", {
  name: /gender/i,
});
userEvent.click(inputElement);
const optionElement = screen.getByRole("option", {
  name: /female/i,
});
userEvent.click(optionElement);

Leave a Reply