Testing Disabled Buttons in React Testing Library

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

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:

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

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:

Copied to clipboard! Playground
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
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

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.