Skip to content

元素不 找到 in DOM 测试

错误信息

                TestingLibraryElementError: Unable 到查找元素通过 role/文本
              

快速摘要

测试 tries 到查找元素 (通过 role, 文本, testId) 但它 doesn't exist in rendered 组件. 元素可能不 是 rendered or 查询是 错误.

为什么发生

  • 元素 isn't rendered — conditional 渲染 hides 它.

  • 查询文本 or role doesn't match rendered 元素.

  • 元素是 rendered asynchronously and 测试 didn't wait.

  • 组件 wasn't rendered 使用正确 Props 到 show 元素.

最小示例

✗ 错误代码
test('shows welcome', () => {
  render(<App loggedIn={false} />);
  // Welcome message only shows when loggedIn is true
  expect(screen.getByText('Welcome')).toBeInTheDocument(); // not found
});
✓ 修复代码
test('shows welcome', () => {
  render(<App loggedIn={true} />);
  expect(screen.getByText('Welcome')).toBeInTheDocument(); // found
});

Provide 正确 Props 所以元素是 rendered, or fix 查询到 match.

如何诊断

  • Use screen.调试() 到 print rendered HTML and see 什么's actually 那里.

  • 检查如果元素是 conditionally rendered and 条件 isn't met.

  • For 异步渲染, use waitFor or findBy 查询 (异步 versions 的 getBy).

  • 验证查询 matches — 检查 role, 文本, testId spelling.

如何修复

  • Fix 查询到 match 实际 rendered 元素.

  • Provide 正确 Props 到触发 conditional 渲染.

  • Use findByText/findbyRole (异步) for 元素那个 appear 之后异步操作.

  • Wrap in waitFor() 如果元素 appears 之后状态更新.

如何预防

  • Use screen.调试() 期间 development 到 see rendered 输出.

  • Prefer findBy* (异步) over getBy* for 异步-rendered 元素.

  • 查询通过 role and accessible name for robust 查询.

相关资源

相关术语

相关课程

← 返回语言