How to Test onChange Events in React Testing Library

Ferenc Almasi • 2022 September 04 • 📖 2 min read

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

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)
    })
})
Copied to clipboard!

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.

expect(select.value).toBe('🎴')
expect(jest.selected).toBe(true)
Copied to clipboard!
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in 5 hours.

Learn More

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
Read more on
🎉 Thank you for subscribing to our newsletter. x