Testing react select with react testing library

Marek Rozmus
2 min readDec 12, 2021
Photo by Edu Grande on Unsplash

There are several ways on the net saying how to test react-select.

After trying many ways found with Google (that didn’t work) I have finally found the official way how it should be done. It can be even found in the official documentation of testing-library here: https://testing-library.com/docs/ecosystem-react-select-event/.

I said yeah, finally! And… it didn’t work at all. It couldn’t select my items on the list.

I tried to follow the documentation and use:

await selectEvent.select(myReactSelectField, 'Existing item')

but what I got was only an error like:

Unable to find an element with the text: Existing item

Maybe because I was using this component with Formik or there was some other magic that was happening.

At least in the documentation I found one important thing. In case of react-select field the inputId and not the id should be used to tag the field. Then we can find the proper input with the methods like: screen.getByLabelName

I tried some other methods from that library and following code worked perfectly:

selectEvent.openMenu(myReactSelectField);
expect(screen.getByText("Existing item")).toBeInTheDocument()

So the item was there but the select method said it wasn’t.

I ended up with dropping usage of that lib and making something like this:

fireEvent.keyDown(myReactSelectField, { key: "ArrowDown" });
const existingItem = await screen.findByText('Existing item')
fireEvent.click(existingItem);

--

--