Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React testing library - Check button disabled attribute

Okay, so I have this input field which requires at-least 10 characters, which enables the button which says Save & Next.

If description.length < 10, it stays disabled. This is working fine in the UI. But I am unable to write a test for it.

test('👉 Disables the save and next button if description < 10', () => {
    render(<StepOne />, { initialState });
    const input = screen.getByLabelText(/description/i);
    fireEvent.change(input, { target: { value: '123456' } }); // 👈 Length < 10
    const button = screen.getByText('Save & Next');
    console.log(button.innerHTML);
    expect(button).toBeDisabled(true);
  });

Error:

expect(element).toBeDisabled()

    ❌ Received element is not disabled:
      <span class="MuiButton-label" />

I wonder what I am missing here

like image 846
Karan Kumar Avatar asked Jul 02 '26 17:07

Karan Kumar


1 Answers

If you debug, you will see how a disabled button is rendered by MUI:

<button
  class="MuiButtonBase-root MuiButton-root MuiButton-text Mui-disabled Mui-disabled"
  disabled=""
  tabindex="-1"
  type="button"
>
  <span class="MuiButton-label">Save & Next</span>
</button>

So, you can use .closest to access the button:

const button = screen.getByText('Save & Next').closest("button");
expect(button).toBeDisabled();
like image 56
Ajeet Shah Avatar answered Jul 05 '26 06:07

Ajeet Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!