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

React测试报错:TestingLibraryElementError无法匹配/learn react/i文本

测试用例「renders learn react link」执行失败详情

错误概述

测试用例执行失败(耗时36ms),触发TestingLibraryElementError:无法找到匹配正则/learn react/i的元素。提示原因:文本可能被多个元素拆分,可使用函数式文本匹配器提升灵活性。
忽略的节点:comments、<script />、<style />

渲染的DOM结构

<body>
  <div>
    <div>
      <div
        class="sc-bczRLJ jlIjgm"
      >
        navbar
      </div>
      <button
        class="sc-gsnTZi bVnXBy"
      >
        Normal Button
      </button>
    </div>
  </div>
</body>

测试代码位置

4 | test('renders learn react link', () => {
  5 |   render(<App />);
> 6 |   const linkElement = screen.getByText(/learn react/i);
    |                              ^
  7 |   expect(linkElement).toBeInTheDocument();
  8 | });
  9 |

错误调用栈

at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:40:19)
at node_modules/@testing-library/dom/dist/query-helpers.js:90:38
at node_modules/@testing-library/dom/dist/query-helpers.js:62:17
at getByText (node_modules/@testing-library/dom/dist/query-helpers.js:111:19)
at Object.<anonymous> (src/App.test.js:6:30)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:404:19)
at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)

测试结果

  • 测试套件:1个失败(共1个)
  • 测试用例:1个失败(共1个)
  • 快照:0个
  • 总耗时:1.499秒
  • 进程退出码:1

解决建议

  1. 检查App组件是否正确渲染了包含"learn react"文本的链接——当前DOM中仅存在"navbar"和"Normal Button"元素,目标元素未出现。
  2. 若文本确实被拆分到多个元素中,改用函数式文本匹配器:
    const linkElement = screen.getByText((content) => content.includes('learn react'));
    

内容的提问来源于stack exchange,提问作者NANDA KUAMR K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:36:32