【问题标题】:How to fetch element with 'name' attribute in react-testing-library如何在 react-testing-library 中获取具有“name”属性的元素
【发布时间】:2021-05-05 06:15:23
【问题描述】:

我正在使用 react 测试库和 jest 测试我的 react 应用程序。

我想知道如何在 react-testing-library 中获取具有 'name' 属性的元素。

例如,在下面的页面中,是否可以使用“userName”获取此元素?

<input type="text" name="userName" />

或者我应该在元素中设置data-testId 并使用getByTestId 方法?

return (
  <div>
    <input type="text" name="userName" />
  </div>
)

【问题讨论】:

    标签: reactjs jestjs react-testing-library


    【解决方案1】:

    您可能想使用getByRole

    screen.getByRole('textbox', { name: 'userName' });
    

    【讨论】:

    • 更多关于 getByRole,testing-library.com/docs/queries/byrole
    • 我发现这行不通。我收到一条错误消息,提示找不到该元素,然后测试运行程序列出了所有具有“文本框”角色的元素,其中之一是:Name "": &lt;input class="chakra-input css-nwrwxl" id="field-5499436576-20" inputmode="numeric" name="subscriptions.0.subscriptionUnits.0.units" placeholder="Quantity" value="1" /&gt;——换句话说,即使具有“名称”属性, react-testing-library 将其名称显示为空字符串,而我的 getByRole 失败...
    • *ByRole 查询中的name 选项指的是元素的可访问名称,而不是其name 属性的值。见What is the name option in react-testing-library?
    【解决方案2】:

    您可以使用返回的containercontainer 是一个 DOM 节点并支持 querySelector method,它接受 CSS 选择器来查找元素。与this more detailed answer 中的方法相同。

    例如:

    const { container } = render(<MyComponent />);
    const inputEl = container.querySelector(`input[name="userName"]`);
    

    【讨论】:

    • 工作就像一个魅力。谢谢!
    猜你喜欢
    • 2022-08-10
    • 2019-03-30
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2020-04-13
    • 2019-03-10
    相关资源
    最近更新 更多