Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading