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.
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}
/>
...
</>
);
}
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();
});
});
I expect the input node to be found by label text, and to be disabled, leading to a passing test.
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.
Well, apparently all I had to do was use stack overflow as a rubber duck, because I immediately figured it out..
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.. 🤣
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With