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

NestJS 9.x Jest单元测试报错:Property 'compile'不存在于OverrideBy类型

解决NestJS 9+ Jest测试中Property 'compile' does not exist on type 'OverrideBy'错误

错误原因

你使用的NestJS 9.0.0+版本已经移除了TestingModuleBuilder的.compile()方法,模块创建会自动完成编译。但测试代码在调用.overrideFilter()后依然显式调用了.compile(),而OverrideBy类型并没有这个方法,因此触发了TS类型错误。

修复步骤

直接移除测试代码中的.compile()调用即可,同时注意overrideFilter需要明确指定过滤器的实现才能生效,修改后的测试代码如下:

describe('MyController', () => {
  let myController: MyController;
  let myService: MyService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [MyController],
      providers: [MyService],
    }).overrideFilter(AppErrorExceptionFilter)
      .useValue(new AppErrorExceptionFilter()); // 指定过滤器实例,确保覆盖生效

    myController = module.get<MyController>(MyController);
    myService = module.get<MyService>(MyService);
  });

  // 示例测试用例
  it('should return data when listData is called', async () => {
    const mockDto: RequestDto = { /* 填充测试用请求数据 */ };
    const mockResult = { /* 预期返回结果 */ };
    jest.spyOn(myService, 'listData').mockResolvedValue(mockResult);

    const result = await myController.listData(mockDto);
    expect(result).toEqual(mockResult);
    expect(myService.listData).toHaveBeenCalledWith(mockDto);
  });
});

另外补充两个代码细节修正建议:

  • 控制器中lsitData存在拼写错误,建议修正为listData,避免后续调用异常
  • 控制器构造函数中private readonly MyService: MYService的变量名与后续this.myService大小写不一致,建议改为private readonly myService: MyService,保持代码一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:15:05