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

NestJS中FileUploadService测试报错求助:求正确测试方法

解决NestJS中FileUploadService测试依赖报错问题

问题代码

service.ts

@Injectable()
export class FileUploadService {
  private readonly logger = new Logger(FileUploadService.name);

  constructor(private readonly httpService: HttpService) {}
}

spec.ts

beforeEach(async () => {
  const app: TestingModule = await Test.createTestingModule({
    imports: [],
    providers: [FileUploadService],
  }).compile();

  fileService = app.get<FileUploadService>(FileUploadService);
});

报错原因

测试模块无法解析HttpService依赖,因为FileUploadService构造函数注入了HttpService,但测试配置中未提供该服务的实例或模拟对象。HttpService来自@nestjs/axios的HttpModule,测试时必须显式声明其依赖。

解决方案

方案1:模拟HttpService(单元测试推荐)

在测试模块的providers中提供一个模拟的HttpService,覆盖真实依赖:

beforeEach(async () => {
  const app: TestingModule = await Test.createTestingModule({
    providers: [
      FileUploadService,
      {
        provide: HttpService,
        useValue: {
          // 根据service实际调用的方法添加对应模拟实现
          post: jest.fn().mockResolvedValue({ data: {} }),
          get: jest.fn().mockResolvedValue({ data: {} })
        }
      }
    ],
  }).compile();

  fileService = app.get<FileUploadService>(FileUploadService);
});

方案2:导入HttpModule(集成测试场景)

若需使用真实的HttpService,可直接导入HttpModule:

import { HttpModule } from '@nestjs/axios';

beforeEach(async () => {
  const app: TestingModule = await Test.createTestingModule({
    imports: [HttpModule],
    providers: [FileUploadService],
  }).compile();

  fileService = app.get<FileUploadService>(FileUploadService);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 08:52:13