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?
This is an example of how you could mock a select: jest. mock("react-select", () => ({ options, value, onChange }) => { function handleChange(event) { const option = options. find( option => option.
data-testid is an attribute used to identify a DOM node for testing purposes. It should be used as a handler to the test code. We need to make sure its value is unique. Therefore, we do not cause conflicts between components.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With