在使用测试库进行测试时使用 getByRole 时无法获取输入的名称

Unable to get the name of the input when using getByRole while testing with 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}}}
            />

我为此编写了测试:

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=""
      />

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

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

根据 docs 我想你想要以下之一

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

<TextField label="code" />

备注

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


有用的链接