Sli*_*lim 9 javascript reactjs react-testing-library
我正在测试一个包含 Material Ui TextField 组件的组件(我们称之为 MyComponent):
<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}}}
/>
Run Code Online (Sandbox Code Playgroud)
我为此编写了测试:
test('Checking the initial rendering of the component', () => {
const initialState = {
refs: {
choice: '',
creationDate: '',
},
};
render(<MyComponent />, {initialState});
expect(screen.getByRole('textbox', {name: /code/i})).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
测试失败,我收到此错误:
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=""
/>
Run Code Online (Sandbox Code Playgroud)
我应该role=textbox 为 TextField 组件添加还是该textbox角色不适用于输入元素?
Dou*_*oug 10
您可以从测试输出中看到您的input元素没有aria-label. 这会导致可访问性名称为空字符串""。
根据文档,我认为您需要以下之一
<TextField inputProps={{ 'aria-label': 'code' }} />
Run Code Online (Sandbox Code Playgroud)
或者
<TextField label="code" />
Run Code Online (Sandbox Code Playgroud)
一个很好的经验法则是尝试在不依赖 aria 属性的情况下使其工作 - 如果没有其他方法,然后再使用它们。阅读更多
| 归档时间: |
|
| 查看次数: |
7351 次 |
| 最近记录: |