Skip to content

多个元素找到

错误信息

                TestingLibraryElementError: 找到多个元素使用 role/文本
              

快速摘要

查询找到更多 than one 元素. getBy* 查询必须查找精确地 one match — use getAllBy* for 多个 matches.

为什么发生

  • 组件渲染多个元素 matching 查询.

  • 查询是 也 broad (e.g., getByRole('button') 使用多个 buttons).

  • 列表渲染创建多个元素使用相同文本.

  • Using getBy* 哪里 getAllBy* 应该是 used.

最小示例

✗ 错误代码
test('click submit', () => {
  render(<Form />);
  // Multiple buttons exist
  const button = screen.getByRole('button'); // error: found 3 buttons
});
✓ 修复代码
test('click submit', () => {
  render(<Form />);
  const button = screen.getByRole('button', { name: 'Submit' }); // specific
});

制作查询更多特定使用 name option 到 match 精确地 one 元素.

如何诊断

  • Use screen.调试() 到 see 所有 rendered 元素.

  • 数量如何许多元素 match 查询.

  • 制作查询更多特定 (e.g., 添加 name option: getByRole('button', { name: '提交' })).

  • Use getAllBy* 如果多个 matches 是 expected.

如何修复

  • 制作查询更多特定: getByRole('button', { name: '提交' }) 相反的 getByRole('button').

  • Use getAllByText/getAllByRole 如果多个 matches 是 expected.

  • Use 在内() 到作用域查询到 特定部分的 DOM.

如何预防

  • 制作查询特定 enough 到 match 精确地 one 元素.

  • Use getAllBy* 当你 expect 多个 matches.

  • Use 在内(容器) 到 narrow 搜索作用域.

相关资源

相关术语

相关课程

← 返回语言