Testing Disabled Buttons in React Testing Library
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()
})
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()
})
π More Webtips
Master the Art of Frontend
Access exclusive interactive lessons
Unlimited access to hundreds of tutorials
Remove ads to learn without distractions