gpt4 book ai didi

javascript - 在使用 testing-library 进行测试时使用 getByRole 时无法获取输入的名称

转载 作者:行者123 更新时间:2023-12-05 00:24:45 27 4
gpt4 key购买 nike

我正在测试一个包含 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}}}
/>
我为此编写了测试:
test('Checking the initial rendering of the component', () => {
const initialState = {
refs: {
choice: '',
creationDate: '',
},
};
render(<MyComponent />, {initialState});
expect(screen.getByRole('textbox', {name: /code/i})).toBeInTheDocument();
});
测试失败,我收到此错误:
 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=""
/>
我应该添加 role=textbox 对于 TextField 组件或 textbox Angular 色不适用于输入元素?

最佳答案

您可以从测试输出中看到您的 input元素没有 aria-label .这会导致可访问性名称为空字符串 "" .
根据 docs我想你想要以下之一

<TextField inputProps={{ 'aria-label': 'code' }} />
或者
<TextField label="code" />

笔记
在不依赖 aria 属性的情况下尝试使其工作是一个很好的经验法则——如果没有其他方法,然后再使用它们。 Read more

有用的链接
  • <TextField />
  • dont overuse aria
  • 关于javascript - 在使用 testing-library 进行测试时使用 getByRole 时无法获取输入的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64864453/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com