0
votes

I am attempting to write a test case to assert that a number input is disabled while a radio option is selected and am having trouble using React Testing Library utils to query for the HTML <input> rendered by a Material UI <TextField>.

There are two <TextField> instances in the component that this test applies to, so I am attempting to use the findAllByLabelText query and then loop through those nodes to confirm the disabled state.

React Component

function OverridePriceModal () {
  ...
  return (
    <>
      ...
      <TextField
        type="number"
        label="Custom Pricing"
        value={regularPriceOverride}
        onChange={evt => setRegularPriceOverride(evt.target.value)}
        disabled={!isRegularPriceOverridden}
      />
      ...
      <TextField
        type="number"
        label="Custom Pricing"
        value={specialPriceOverride}
        onChange={evt => setSpecialPriceOverride(evt.target.value)}
        disabled={!isSpecialPriceOverridden}
      />
      ...
    </>
  );
}

Unit Test

test('custom price inputs are disabled while following system pricing', async () => {
  render(<OverridePriceModal />);

  const priceInputs = await screen.findAllByLabelText('Custom Pricing');
  _.forEach(priceInputs, input => {
    expect(input).toBeDisabled();
  });
});

Expected Results

I expect the input node to be found by label text, and to be disabled, leading to a passing test.

Actual Results

I receive the following error message in test output:

Found a label with the text of: Custom Pricing, however no form control was found associated to that label. Make sure you're using the "for" attribute or "aria-labelledby" attribute correctly.

1

1 Answers

1
votes

Well, apparently all I had to do was use stack overflow as a rubber duck, because I immediately figured it out..

Solution

Simply add id prop to <TextField>.

The label and input within the MUI TextField are not properly linked with the for attribute unless you provide the id prop, as noted under the Accessibility section of the MUI TextField docs.

Maybe unit tests will force best practices on me after all.. 🤣