How to Test onChange Events in React Testing Library

Ferenc Almasi β€’ 2022 September 04 β€’ Read time 2 min read
  • twitter
  • facebook

To test onChange events in React Testing Library, use the fireEvent.change API in the following way:

Copied to clipboard! Playground
import React from 'react'
import { fireEvent, render, screen } from '@testing-library/react'

describe('onChange events', () => {
    it('should test onChange behavior', () => {
        render(<Dropdown />)

        const select = screen.getByRole('select')
        const testingLibrary = screen.getByRole('option', { name: 'React Testing Library' })
        const jest = screen.getByRole('option', { name: 'Jest' })

        fireEvent.change(select, { target: { value: 'πŸ™' } })

        expect(select.value).toBe('πŸ™')
        expect(testingLibrary.selected).toBe(true)

        fireEvent.change(select, { target: { value: '🎴' } })

        expect(select.value).toBe('🎴')
        expect(jest.selected).toBe(true)
    })
})

To select an option from an HTML select element, you will need to grab the element with either screen.getByTestId or screen.getByRole, and pass it over to fireEvent.change with a target.value object for targeting the right option.

Notice that you can also grab elements by specifying the value of their attributes inside an object, passed as a second parameter to screen.getByRole.

Finally, to test if the correct element is selected, we can use select.value and option.selected for assertions.

Copied to clipboard!
expect(select.value).toBe('🎴')
expect(jest.selected).toBe(true)
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.