material-ui - React-Testing-Library 找不到具有给定角色和名称的组件

标签 material-ui react-testing-library react-hook-form

我有一个带有动态生成名称的输入,我想用 react-testing-library 选择它。 RTL 不检测输入,即使 CLI 错误输出包含具有正确名称和角色的元素。

以下是测试代码的摘录:

const attributeInput = await getByRole(container, 'textbox', {name: 'attributes[0].value'});
await waitFor(() => {
      expect(attributeInput).toBeTruthy();
});

测试报错信息如下:

TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name "attributes[0].value"

Here are the accessible roles:

... (list of accessible roles and inputs of different types with various names, omitted for brevity) ...

  --------------------------------------------------
  textbox:

  Name "":
  <input
    aria-invalid="false"
    class="MuiInputBase-input MuiOutlinedInput-input"
    name="attributes[0].value"
    rows="1"
    type="text"
    value=""
  />

很明显,该元素在容器中,角色为“文本框”,并且有一个名称属性,其值“attributes[0].value”与其相关联。那么,为什么 RTL 没有注册这个类型和名称正确的组件,这就是我要找的组件?为什么会出错

Name: ""

在命令行输出?

可能相关:我正在使用 material-ui 并且此 HTML 是从包装在 react-hook-form Controller 中的 TextField 生成的。此外,这个断言是在之前的一些 react-testing-library 操作之后到达的,这些操作以编程方式导航到这个页面并期望看到这个输入。之前的“gets”“acts”或“waitFor/expects”都没有失败,并且许多其他输入的名称被 react-testing-library 识别(尽管 RTL 分配给它们的名称似乎是它们的 InputLabel 文本和而不是分配给生成的 HTML 上的“名称”属性的内容。

最佳答案

对于任何异步操作,建议不要使用 getBy,而是请尝试使用 findByRole/findAllByRole 方法。 引用:

  [
                { name: 'Chocolate', imagePath: '/images/chocolate.png' },
                { name: 'Vanilla', imagePath: '/images/vanilla.png' },
            ]
  test("display each impage of scoop as response api", async () => {
    render(<Options optionType="scoops" />);

    // Find images
    const scoopImages =  await screen.findAllByRole('img', {
        name: /scoop$/i
    });
    expect(scoopImages).toHaveLength(2);

    const altText = scoopImages.map((elem) => elem.alt);
    expect(altText).toEqual('Chcolate scoop', 'Vanilla scoop');
})

关于material-ui - React-Testing-Library 找不到具有给定角色和名称的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66700364/

相关文章:

reactjs - React Hooks - 如何测试全局提供者的更改

javascript - 带有来自异步源的嵌套字段数组的 React hook 表单返回空数组

html - Cypress :如何测试 HTML5 内置的验证弹出窗口?

html - Chrome 自动填充会导致文本字段标签和值的文本框发生冲突

material-ui - 如何在 material-ui 中自定义复选框的颜色

reactjs - 如何在react-testing-library中测试父子关系?

reactjs - React hook 表单如何将值从自定义组件传递到已在更改时分配自己的 Controller ?

javascript - 有没有办法更改 Material ui的自动完成组件上的关闭图标?

css - Material UI - 设置输入占位符文本的样式

javascript - 我将如何在 react 测试库中测试 react 路由器路由参数?