Testing Disabled Buttons in React Testing Library

Ferenc Almasi • 2022 September 04 • 📖 1 min read

To test whether your buttons are disabled or not in React Testing Library, you need to use the toHaveAttribute or the toBeDisabled assertion in the following way:

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

it('should render a disabled button', () => {
    render(<Cta disabled={true}>Learn more!</Cta>)

    expect(screen.getByTestId('button')).toHaveAttribute('disabled')
    expect(screen.getByTestId('button')).toBeDisabled()
})
Testing disabled buttons in React Testing Library
Copied to clipboard!

toHaveAttribute also accepts a second parameter for the value if you need to test specific attribute values.

Prefer using getByTestId to avoid breaking your unit tests by small code changes. You can also test the opposite and verify if your buttons are not disabled by prepending a not to either of the assertions:

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

it('should render a disabled button', () => {
    render(<Cta>Learn more!</Cta>)

    expect(screen.getByTestId('button')).not.toHaveAttribute('disabled')
    expect(screen.getByTestId('button')).not.toBeDisabled()
})
Testing if the button is NOT disabled
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