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

React单元测试waitFor超时问题求助:已Mock接口仍报错

解决React组件单元测试waitFor超时问题

问题场景

正在进行React组件单元测试,已MockfetchAppList和fetchTotalAppCount接口,但渲染IntegrationsPage组件时,执行waitFor查询元素持续出现超时错误。

报错信息

● loads the correct number of apps

    Timed out in waitFor.

      11 |     render(<IntegrationsPage/>);
      12 |
    > 13 |     const appList = await waitFor(() => screen.findAllByText("Notify me when it's ready"));
         |                                  ^
      14 |     expect(appList).toHaveLength(10);
      15 | });

      at waitForWrapper (node_modules/@testing-library/dom/dist/wait-for.js:187:27)
      at Object.<anonymous> (src/pages/integrations/IntegrationsPage.test.js:13:34)

测试代码

import { render, screen, waitFor } from "@testing-library/react";
import IntegrationsPage from "./IntegrationsPage";
import apps from "../../api/apps/Apps";
import mockData from "../../api/apps/MockData";

jest.mock("../../api/apps/Apps");

test("loads the correct number of apps", async() => {
    apps.fetchAppList.mockResolvedValue(mockData);
    apps.fetchTotalAppCount.mockImplementation(() => mockData.length);
    render(<IntegrationsPage/>);

    const appList = await waitFor(() => screen.findAllByText("Notify me when it's ready"));
    expect(appList).toHaveLength(10);
});

组件useEffect逻辑

useEffect(() => {
        const totalAppCount = Apps.fetchTotalAppCount()
        const pageCount = calculatePageCount(totalAppCount);

        Apps
        .fetchAppList(INITIAL_OFFSET,ITEMS_PER_PAGE)
        .then((result) => {
            setCurrentPage(INITIAL_PAGE);
            setTotalAppCount(totalAppCount);
            setPageCount(pageCount);
            setAppList(result);
        });

    },[]);

排查与解决

  • 移除冗余的waitFor包裹:findAllByText本身就是异步查询方法,内部已集成waitFor的等待逻辑,无需额外嵌套。修改测试代码:

    const appList = await screen.findAllByText("Notify me when it's ready");
    expect(appList).toHaveLength(10);
    
  • 校验分页参数与Mock数据匹配:组件调用fetchAppList时传入了INITIAL_OFFSET和ITEMS_PER_PAGE参数,需确保mockData长度与ITEMS_PER_PAGE一致,或让Mock函数忽略参数直接返回完整数据。若ITEMS_PER_PAGE设为5但mockData长度为10,组件只会渲染5个条目,导致断言失败超时。

  • 检查Mock数据结构有效性:确认mockData中的每个条目都能触发子组件渲染"Notify me when it's ready"文本,若部分条目缺少必要属性,会导致实际渲染数量不足10,引发超时。

  • 验证状态更新逻辑:检查组件中setAppList(result)是否正确更新状态,是否存在过滤、排序等逻辑减少了渲染的列表数量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:40:52