Properly Testing Button Clicks in React Testing Library

Ferenc Almasi β€’ 2022 September 03 β€’ πŸ“– 1 min read

In order to test button click events in React Testing Library, we need to use the fireEvent API:

import { fireEvent, render, screen } from '@testing-library/react'

it('Should expand and collapse an accordion', () => {
    render(<Accordion>Content</Accordion>)
    
    // Prefer using getByTestId or getByRole
    const button = screen.getByTestId('accordionButton')
    const button = screen.getByRole('button')
    const button = screen.getByText('Collapse')

    expect(screen.queryByText('Content')).toBeNull()

    fireEvent.click(button)

    expect(screen.getByText('Content')).toBeInTheDocument()

    fireEvent.click(button)

    expect(screen.queryByText('My Content')).toBeNull()
})
Copied to clipboard!

Once you have the rendered component, you will need to grab the button using screen.getByTestId. you can also use other methods such as getByRole or getByText, but preferably, you want to use getByTestId to avoid breaking your test cases by changing the copy.

Then you can call fireEvent.click and pass the queried button to simulate a click event. Notice that you can fire the same event multiple times. In the above example, we try to verify if the accordion can be opened and closed with two different click events.

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 less than 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
Ezoicreport this ad
πŸŽ‰ Thank you for subscribing to our newsletter. x