I'm testing a component (let's call it MyComponent) which contains a Material Ui TextField component:
<TextField
name="code"
aria-label="code"
onKeyPress={keyPressHandler(codeRegExp)}
value={values.code}
placeholder={codePlaceholder}
onChange={handleChange}
InputProps={{
classes: {
input: classes.code,
},
}}
onBlur={handleBlur}
helperText={
touchedValues.code && errorValues.code ? errorValues.code : ''
}
FormHelperTextProps={{classes: {root: classes.errorMessage}}}
/>
I wrote the test for that:
test('Checking the initial rendering of the component', () => {
const initialState = {
refs: {
choice: '',
creationDate: '',
},
};
render(<MyComponent />, {initialState});
expect(screen.getByRole('textbox', {name: /code/i})).toBeInTheDocument();
});
The test fails and I got this error:
TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name `/code/i`
Here are the accessible roles:
textbox:
Name "":
<input
aria-invalid="false"
class="MuiInputBase-input MuiInput-input makeStyles-code-9"
name="code"
placeholder="ABC_123"
type="text"
value=""
/>
Should I add the role=textbox
for the TextField Component or does the textbox
role does not works with input elements?
To find elements by className in React testing library: Render a component and destructure the container object from the result. Use the getElementsByClassName() method on the container to find elements by class name.
You can also query the returned element(s) by their accessible name by specifying the name argument: getByRole(expectedRole, name: 'The name') . The accessible name is for simple cases equal to the label of a form element, or the text content of a button, or the value of the aria-label attribute.
getByText() ) return the matching DOM node for a query, or throw an error if no element is found.
You can see from the test output that your input
element does not have aria-label
. This causes the accessibility name to be an empty string ""
.
As per docs I think you want one of the following
<TextField inputProps={{ 'aria-label': 'code' }} />
or
<TextField label="code" />
It is a good rule of thumb to try make it work without relying on aria properties first--and then using them if there is no other way. Read more
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