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

Jest测试中Mock的fetchBusinessListing失效 无法找到gridcell元素

问题原因分析
  • 第一点:Mock 导出格式与原模块不匹配
    原services/business-listing模块使用命名导出的方式暴露fetchBusinessListing方法,但你的jest.mock将整个模块导出为一个函数,导致组件导入的fetchBusinessListing实际为undefined,调用时报「不是函数」的错误。API调用失败后不会给listing赋值,自然找不到gridcell元素。
  • 第二点:测试未包裹Redux Provider
    组件内部使用了useDispatch来自react-redux,测试中直接渲染组件时没有外层Provider提供store上下文,useDispatch会抛出异常,打断后续代码执行,同样会导致数据无法正常渲染。
修复方案

首先修正mock的写法,对齐原模块的导出结构:

const bizListing = [
  // 你的假数据
];
jest.mock("../../services/business-listing", () => ({
  // 对应原模块的命名导出
  fetchBusinessListing: jest.fn().mockResolvedValue({
    success: true,
    data: bizListing
  })
}));

其次在渲染组件时包裹Redux Provider,推荐搭配redux-mock-store使用:

  1. 先安装依赖:npm install redux-mock-store --save-dev
  2. 修改测试代码如下:
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';

// 初始化mock store
const mockStore = configureStore([]);
const testStore = mockStore({
  // 可根据需要填写测试用的初始state
});

afterEach(cleanup);

describe('BizCard', () => {
  test("loading listing", async () => {      
    useSession.mockReturnValueOnce([null, false]);      
    
    await act(async () => {
      render(
        <Provider store={testStore}>
          <BizCard />
        </Provider>
      )
    });      
    
    const itemGrid = await screen.findAllByRole("gridcell");
    expect(itemGrid).not.toHaveLength(0);
  });
});

额外注意:确保你的假数据bizListing的每个条目包含key、id、name等BizCardItem需要的属性,避免渲染异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:48:02