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

Jest.fn().mockReturnValue返回undefined 无法读取collection属性排查

问题原因

你遇到的报错核心原因是Jest API拼写错误:
你在setupTests.js中为firestore mock函数设置返回值时,错误使用了不存在的mockReturnedValue方法,正确的API名称为mockReturnValue。
因为拼写错误,mock的firestore函数没有被正确配置返回值,调用firebase.firestore()时默认返回undefined,后续调用undefined.collection()就触发了Cannot read property 'collection' of undefined报错。

解决方案

如果你需要保留jest.fn()写法(方便后续测试用例中统计firestore的调用次数、传参等),修正拼写即可:

jest.mock('./firebase', () => ({
  storage: jest.fn(),
  // 把mockReturnedValue改为mockReturnValue
  firestore: jest.fn().mockReturnValue({
    collection: jest.fn().mockReturnThis(),
    orderBy: jest.fn().mockReturnThis(),
    onSnapshot: jest.fn().mockReturnThis(),
  }),
}));

你修改后的写法直接给firestore赋值为普通函数,绕开了错误的Jest API调用,因此可以正常运行。

额外提示:你原firebase.js还导出了命名导出serverTimestamp,如果你的业务代码有引用这个导出,需要在mock中补充对应实现,否则会触发新的导出缺失报错,参考完整mock写法:

jest.mock('./firebase', () => ({
  __esModule: true, // 兼容ES模块导出规则
  default: {
    storage: jest.fn(),
    firestore: jest.fn().mockReturnValue({
      collection: jest.fn().mockReturnThis(),
      orderBy: jest.fn().mockReturnThis(),
      onSnapshot: jest.fn().mockReturnThis(),
    }),
  },
  serverTimestamp: jest.fn()
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:54:05