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

标签 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}}}
            />
我为此编写了测试:
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/

    相关文章:

    javascript - 在组件外部使用 redux 钩子(Hook)来实现代码的可重用性

    javascript - angularjs用不同的函数定义值

    javascript - 函数 createIdentityMatrix(a,b)

    javascript - Google map 自定义标记

    javascript - 如何使用实际模块而不是使用模拟

    reactjs - 如何使用 React 测试库和 Jest 测试错误 get api request React query useInfiniteQuery?

    reactjs - react-testing-library 测试 Ant Design modal

    javascript - 测试库错误 : mockConstructor(. ..):渲染没有返回任何内容

    JavaScript 闭包行为异常

    javascript - 我无法仅使用 javascript 在 5 秒后执行引导模式以在页面上弹出。