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

Nestjs框架下Jest手动mock CatalogueService不生效报错排查

问题原因

你遇到的报错是因为__mock__下的手动mock文件没有被正确加载/执行,jest fallback到了默认的自动mock逻辑:自动mock的类方法默认返回undefined,调用subscribe自然就抛出了Cannot read property 'subscribe' of undefined错误。

手动mock文件加载失败基本都是语法错误、依赖缺失导致的,按以下步骤修复即可:


解决步骤

  1. 修复mock文件的语法错误
    你写的filterRulesFor方法末尾缺少闭合括号和分隔逗号,会直接导致语法解析失败,修改/catalogue/__mock__/catalogue.service.ts里的对应代码:
// 修复前
filterRulesFor: jest.fn().mockImplementation((role: Roles): Rule[] => rules.filter(r => r.roles.includes(role))
// 修复后(加了闭合括号和逗号)
filterRulesFor: jest.fn().mockImplementation((role: Roles): Rule[] => rules.filter(r => r.roles.includes(role))),
  1. 补全mock文件的所有依赖和变量定义
    检查__mock__/catalogue.service.ts文件,确保所有用到的内容都正确导入/定义,完整的mock文件参考:
// /catalogue/__mock__/catalogue.service.ts
import { of } from 'rxjs'; // 必须导入of操作符
import { Roles, Rule, Country } from '../你对应的类型文件路径'; // 导入用到的类型
import { countriesStub } from '../你对应的stub文件路径'; // 导入countriesStub

// 定义你用到的rules变量,不要直接用未定义的变量
const mockRules: Rule[] = [
  // 你自己的mock规则数据
];

export const CatalogueService = jest.fn().mockImplementation(() => {
  return {
    filterRulesFor: jest.fn().mockImplementation((role: Roles): Rule[] => mockRules.filter(r => r.roles.includes(role))),
    fetchCountries: jest.fn().mockReturnValue(of(countriesStub())),
  }
});
  1. 检查文件名匹配性
    确保__mock__下的mock文件名、大小写和原服务文件完全一致,比如原文件是Catalogue.service.ts,mock文件也要写成Catalogue.service.ts,避免大小写不匹配导致Linux等区分大小写的系统无法加载mock文件。

  2. 验证生效(可选)
    你可以在测试文件的beforeEach中加一行日志验证mock是否正常加载:

service = module.get<CatalogueService>(CatalogueService);
console.log(service.fetchCountries); // 正常会输出jest mock函数,不是undefined
jest.clearAllMocks();

内容的提问来源于stack exchange,提问作者Jonathan Gómez Pérez

相关产品推荐
方舟 Agent Plan

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

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