How to test a select element with React Testing Library

Search for a command to run...

Thanks for sharing this Cathal Mac Donnacha.
I didn't know I could do
expect(screen.getByRole('option', { name: 'Select a country' }).selected).toBe(true)
Yea it's a much more reliable way of checking it. Glad you found it useful. π
Getting error in -> β should allow user to change country.
FAIL src/components/App.test.js
β should allow user to change country
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: false
27 | screen.getByRole('option', {name: 'Ireland'}),
28 | )
> 29 | expect(screen.getByRole('option', {name: 'Ireland'}).selected).toBe(true)
| ^
30 | })
31 |
Hey, is this in the codesandbox test? Seems to be working fine for me.
screen.getByRole('option', { name: 'Ireland' }), for this getting error as multiple elements found out with role options. Throwing error at getByRole not going to the name condition
Hey ankur dhull
Thanks for reading.
When it comes to select element options, I wouldn't expect there to be any duplicates (e.g options with the same name). If you put a live example up on codesandbox or somewhere similar I can take a look.
Cheers, Cathal.
After noticing a spike in failing Jest builds, I decided to investigate and found that slow and flaky tests were the main culprits. In this article, I go through some tips I discovered for making slow or flaky tests faster and more reliable. There ar...

Code splitting is a technique used to optimize the loading performance of web apps by breaking down the bundled JavaScript files into smaller, more manageable chunks. By loading only the required code for a specific route or page, route-based code sp...

One of the less exciting things about being a Frontend Developer is having to handle error, empty and loading states. It may not be the most fun thing to do, but it's necessary in order to give your users the best experience possible. Thankfully, Moc...

Learn how to migrate your CRA app over to Vite.

Learn how to set up ESLint & Prettier in your ViteJS project.

I recently needed to add tests for a <select> element I was developing, and I couldn't find a lot of resources on how to do this with React Testing Library, so I'll share the approach I went with.
<select> elementFirst of all, let's create a <select> element with some options. Here I have an array with 3 countries:
const countries = [
{ name: "Austria", isoCode: "AT" },
{ name: "United States", isoCode: "US" },
{ name: "Ireland", isoCode: "IE" },
]
Here's the <select> element itself, it has:
A default placeholder <option> asking the user to "Select a country".
A .map method so we can iterate over the countries array and add an <option> element for each one.
<select>
<option>Select a country</option>
{countries.map(country => (
<option key={country.isoCode} value={country.isoCode}>
{country.name}
</option>
))}
</select>
Now that we have a basic <select> element which displays some countries, let's go ahead and write some tests! Yay...my favourite part π
The beauty of React Testing Library is that it makes you focus more on writing tests the way an actual user would interact with your application, so that's the approach I've taken with the tests below. Of course you may have your own unique scenarios, if you do, just think "How would a real user interact with my select element?".
it('should correctly set default option', () => {
render(<App />)
expect(screen.getByRole('option', { name: 'Select a country' }).selected).toBe(true)
})
it('should display the correct number of options', () => {
render(<App />)
expect(screen.getAllByRole('option').length).toBe(4)
})
it('should allow user to change country', () => {
render(<App />)
userEvent.selectOptions(
// Find the select element, like a real user would.
screen.getByRole('combobox'),
// Find and select the Ireland option, like a real user would.
screen.getByRole('option', { name: 'Ireland' }),
)
expect(screen.getByRole('option', { name: 'Ireland' }).selected).toBe(true)
})
Initially when I started to look into writing tests for these scenarios I went with the following approach:
it('should allow user to change country', () => {
render(<App />)
userEvent.selectOptions(
screen.getByRole('combobox'),
screen.getByRole('option', { name: 'Ireland' } ),
)
expect(screen.getByRole('option', { name: 'Ireland' })).toBeInTheDocument();
})
Notice the difference? I was only checking that the "Ireland" <option> existed instead of checking if it was actually selected. Yet my test was still passing π€
expect(screen.getByRole('option', { name: 'Ireland' })).toBeInTheDocument();
Let's take a look at why this happened. When the component is loaded, the following is rendered:
<select>
<option value="">Select a country</option>
<option value="US">United States</option>
<option value="IE">Ireland</option>
<option value="AT">Austria</option>
</select>
So from JSDOM's point of view, the "Ireland" <option> always exists within the document, causing my test to pass!
Whereas the correct approach is to use .selected:
expect(screen.getByRole('option', { name: 'Ireland' }).selected).toBe(true);
Gotchas like this can be just as dangerous as not writing the test in the first place as it gives you false confidence about your tests. This is why I always recommend intentionally causing your tests to fail, like this:
expect(screen.getByRole('option', { name: 'Austria' }).selected).toBe(true);
β Test failed: should allow user to change country
Expected: true
Received: false
This way you can be confident that it only passes for the intended scenario π₯³
Here's a codesandox which includes the basic examples shown above.
So there it is, you should now be able to write some basic tests for your <select> elements using React Testing Library. Of course, I'm not an expert on this topic, I'm simply sharing what I learned in the hope that I can pass on some knowledge.
If you found this article useful, please give it a like and feel free to leave any feedback in the comments π
I mainly write about real tech topics I face in my everyday life as a Frontend Developer. If this appeals to you then feel free to follow me on BlueSky. π¦
Bye for now π