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

NestJS+Jest+Supertest测试控制器遇TypeError问题求助

NestJS Jest测试报错排查:this.graphInspector.insertEnhancerMetadataCache is not a function

问题场景

在monorepo环境下,使用NestJS、Jest和Supertest编写控制器测试用例,测试代码如下:

import * as request from 'supertest';
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { IzvodiNalogModule } from './izvodi_nalog.module';
import { AppModule } from 'src/app.module';

describe('izvodi_nalog', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule, IzvodiNalogModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it(`/GET find modal fields`, async () => {
    const response = await request(app.getHttpServer())
      .get('/izvodi/modal-data')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200);

    expect(response.body).toBeDefined();
  });

  afterAll(async () => {
    await app.close();
  });
});

执行命令 yarn jest -- izvodi_nalog.controller.spec.ts 时出现两个关联错误:

  1. TypeError: this.graphInspector.insertEnhancerMetadataCache is not a function
  2. Cannot read properties of undefined (reading 'close')

主分支已验证过的其他包测试也出现相同错误,排除业务代码问题。

排查方向

  • 依赖版本不一致:monorepo中可能存在NestJS核心包(如@nestjs/core、@nestjs/testing)跨包版本不匹配,graphInspector是NestJS内部用于元数据处理的模块,版本差异会导致方法不存在。执行 yarn why @nestjs/core 或 npm ls @nestjs/core 检查所有子包的依赖版本,确保统一。
  • 缓存冲突:monorepo的Jest缓存或node_modules缓存可能损坏。执行以下操作清理缓存:
    • 清理Jest缓存:yarn jest --clearCache
    • 删除根目录和所有子包的node_modules:rm -rf node_modules */node_modules
    • 重新安装依赖:yarn install
  • Jest配置问题:monorepo的Jest全局配置(如jest.config.js)可能存在模块解析错误,或未正确设置preset: '@nestjs/jest'。检查根目录的jest配置,确保启用NestJS预设,且模块路径映射正确。
  • Monorepo workspace配置问题:package.json中的workspaces配置可能导致依赖安装不完整,或子包未正确继承根依赖。检查根package.json的workspaces字段,确保所有需要测试的子包都被包含。
  • 测试模块初始化问题:测试中同时导入AppModule和IzvodiNalogModule可能导致模块重复初始化,触发内部元数据处理异常。尝试只导入IzvodiNalogModule并手动提供其依赖(如使用providers替换外部依赖),避免加载整个AppModule。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 22:45:13