首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用testing-library进行测试时使用getByRole时无法获取输入的名称

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

Stack Overflow用户
提问于 2020-11-17 03:26:33
回答 1查看 11K关注 0票数 10

我正在测试一个包含材料Ui TextField组件的组件(让我们称其为MyComponent):

代码语言:javascript
复制
<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}}}
            />

我为此编写了测试:

代码语言:javascript
复制
test('Checking the initial rendering of the component', () => {
    const initialState = {
      refs: {
        choice: '',
        creationDate: '',
      },
    };
    render(<MyComponent />, {initialState});
    expect(screen.getByRole('textbox', {name: /code/i})).toBeInTheDocument();
  });

测试失败,我得到了这个错误:

代码语言:javascript
复制
 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=""
      />

我应该为TextField组件添加role=textbox,还是textbox角色不适用于输入元素?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-17 13:06:27

您可以从测试输出中看到您的input元素没有aria-label。这会导致辅助功能名称为空字符串""

根据docs的说法,我认为您需要以下其中一项

代码语言:javascript
复制
<TextField inputProps={{ 'aria-label': 'code' }} />

代码语言:javascript
复制
<TextField label="code" />

备注

一条很好的经验法则是,首先尝试让它在不依赖aria属性的情况下工作,然后在没有其他方法的情况下使用它们。Read more

有用的链接

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64864453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档