如何在Jest/RTL中通过属性名定位select DOM元素并测试值变更
定位元素的定位问题
你之前使用role: 'select'是错误的——原生<select>元素对应的ARIA role是combobox,并不存在名为select的ARIA角色。
如果你的<select>仅通过name="element"标识,没有关联的<label>或其他可访问名称,最直接的定位方式是使用byName查询(它会匹配表单元素的name属性):
// 同步查询(元素已加载完成时) const selectElement = screen.getByName('element'); // 异步查询(元素需要等待渲染时) const selectElement = await screen.findByName('element');
如果坚持使用byRole查询,需要确保<select>有明确的可访问名称。你可以给元素添加aria-label属性:
<select name='element' aria-label='目标选择器'> <option value='1'>First element</option> <option value='2'>Second element</option> <option value='3'>Third element</option> </select>
此时就能通过byRole定位:
const selectElement = await screen.findByRole('combobox', { name: '目标选择器' });
二、测试
相关产品推荐
相关产品推荐

