Unable to get the name of the input when using getByRole while testing with testing-library
·
Answer a question
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?
Answers
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" />
Note
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
Useful links
- <TextField />
- dont overuse aria
更多推荐
所有评论(0)