You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Testing Library无法获取输入组件,如何通过name属性定位?

问题

我想要检查输入组件的值,当值等于Afghanestan(注:原提问写为afghanistans,DOM中实际值为Afghanestan)时测试通过。请问是否可以通过name属性otherNames[0]访问该组件?

提供的DOM结构如下:

<div>
  <div>
    <div>
      <div>
        <label>Other Names</label>
      </div>
    </div>
    <div>
      <div>
        <div role="input">
          <input name="otherNames[0]" type="text" class="MuiInputBase-input MuiInput-input" value="Afghanestan">
        </div>
      </div>
    </div>
  </div>
</div>
<div>
  <div>
    <div>
      <div>
        <div>
          <input name="otherNames[1]" type="text" data-testid="Input-inner" value="">
        </div>
      </div>
    </div>
  </div>
</div>

我目前尝试了以下代码,但返回undefined:

screen.getByRole('textbox',{name:"otherNames[0]"})
解答

问题原因

你误用了getByRole的name选项:该选项对应的是元素的可访问名称(比如关联的<label>文本、aria-label属性值等),而非HTML原生的name属性值。你的第一个输入框和<label>Other Names</label>关联,它的可访问名称是Other Names,不是otherNames[0],所以之前的查询找不到目标元素。

解决方法

方法1:通过关联标签文本查找(推荐)

利用输入框与<label>的关联关系,用getByLabelText直接定位——这是Testing Library推荐的、符合用户实际操作逻辑的查询方式:

// 获取目标输入框
const input = screen.getByLabelText('Other Names');
// 验证输入框值是否符合预期
expect(input).toHaveValue('Afghanestan');

方法2:通过HTML name属性查找

如果必须基于name属性定位,可结合querySelector使用(注意:Testing Library优先推荐语义化查询,此方式适合特殊场景):

const input = screen.querySelector('input[name="otherNames[0]"]');
expect(input).toHaveValue('Afghanestan');

也可以用getByRole并指定正确的可访问名称:

const input = screen.getByRole('textbox', { name: 'Other Names' });
expect(input).toHaveValue('Afghanestan');

方法3:通过显示值查找

若明确知道输入框的预期值,可直接用getByDisplayValue定位并验证:

expect(screen.getByDisplayValue('Afghanestan')).toBeInTheDocument();

内容的提问来源于stack exchange,提问作者SilverRetriever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 17:42:23