Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an option from a select list with React Testing Library

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?

like image 337
Evanss Avatar asked Sep 15 '19 18:09

Evanss


People also ask

How do you mock select in react?

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.

What is data Testid?

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.


1 Answers

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

like image 66
misolo Avatar answered Sep 22 '22 11:09

misolo