reactjsreact-testing-libraryreact-test-rendererreact-testing

How to write test cases for Select Box onChange Method in React Testing Library?


I have a Select Box and set the data in a state by the onChange event. Please have a look at the below code. Anyone can help me to write cases for this onChange event in React Testing Library.

const [optionValue, setOptionValue] = useState({ value: '', label: '' })

const handleOnChange = (option: OptionType): void => setOptionValue(option)

<Select name={title} id={title} placeholder="Choose an Option" options={setOptionsData} defaultOption={optionValue} onChange={e => { handleOnChange(e) }} data-test="options" />


Solution

  • I'd recommend using userEvent which comes as part of the React Testing Library ecosystem. It allows you to write tests which are closer to real user behaviour. Example:**

    it('should correctly set default option', () => {
      render(<App />)
      expect(screen.getByRole('option', {name: 'Make a choice'}).selected).toBe(true)
    })
    
    
    it('should allow user to change country', () => {
      render(<App />)
      userEvent.selectOptions(
        // Find the select element
        screen.getByRole('combobox'),
        // Find and select the Ireland option
        screen.getByRole('option', {name: 'Ireland'}),
      )
      expect(screen.getByRole('option', {name: 'Ireland'}).selected).toBe(true)
    })
    

    Have a look at this article (which I wrote myself) for more info on how to test select elements using React Testing Library.