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

React测试报错:无法找到文本'Camera 1'的解决方案咨询

React测试问题:点击按钮后无法验证列表项存在

问题说明

我是React测试新手,正在通过编码实践学习。需要测试点击“cameras”按钮后展开相机列表(包含Camera 1、Camera 2等选项)的功能。目前能成功定位并点击“cameras”按钮,但验证“Camera 1”是否存在于文档时失败。

报错信息

TestingLibraryElementError: Unable to find an element with the text: Camera 1. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

测试代码

import {
  render,
  screen,
  RenderResult,
  cleanup,
  fireEvent,
  getByRole,
  getByDisplayValue,
  getByText,
} from "@testing-library/react";


describe("Testing component", () => {
  test("Testing Camera", async () => {
    const { getByLabelText, getByTestId, getByText, getByRole } = render(
      <Provider store={store}>
        <CardComponent
          classes={{
            formControl: "",
           
          }}
        />
      </Provider>
    );

    let Cameras = screen.getByRole("button", { name: /cameras/i });
    fireEvent.click(
      Cameras,
      new MouseEvent("click", {
        bubbles: true,
        cancelable: true,
      })
    );

    const screenText = screen.getByText("Camera 1");
    expect(screenText).toBeInTheDocument();
  });
});

界面截图

相机列表展开界面

解决办法

  • 处理文本拆分问题:根据报错提示,“Camera 1”的文本可能被多个DOM元素拆分,不要用精确字符串匹配,改用正则表达式或函数匹配:

    // 正则匹配(忽略大小写)
    screen.getByText(/Camera 1/i);
    // 函数匹配,判断文本是否包含目标内容
    screen.getByText((content) => content.includes("Camera 1"));
    
  • 处理异步渲染:点击按钮展开列表可能涉及状态更新或异步操作,需用waitFor等待元素渲染完成:

    import { waitFor } from '@testing-library/react';
    
    // 点击按钮后
    await waitFor(() => {
      expect(screen.getByText(/Camera 1/i)).toBeInTheDocument();
    });
    
  • 排查DOM渲染情况:在点击按钮后调用screen.debug()打印当前DOM结构,确认“Camera 1”是否真的被渲染,排查是否是组件逻辑问题而非测试代码问题:

    fireEvent.click(Cameras);
    screen.debug(); // 打印当前DOM
    
  • 统一查询方法:测试中同时从render结果和screen导入了查询方法,建议统一使用screen上的查询方法,保持代码一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:15:19