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

NestJS单元测试中HttpService未被正确模拟或注入的问题

NestJS单元测试模拟HttpService报错:TypeError: Cannot read properties of undefined (reading 'get')

我在为NestJS服务编写单元测试时,需要模拟HttpService,但测试返回错误:TypeError: Cannot read properties of undefined (reading 'get')。尽管air-gateway.service模块使用了@Injectable装饰器,测试环境中的httpService始终未定义。

air-gateway.service.spec.ts

import { AirGatewayService } from './air-gateway.service';
import { HttpService } from '@nestjs/axios';
import { createMock, DeepMocked } from '@golevelup/ts-jest';
import { Test, TestingModule } from '@nestjs/testing';

describe('AirGateway Service', () => {
  let service: AirGatewayService;
  let httpService: DeepMocked<HttpService>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        AirGatewayService,
        {
          provide: HttpService,
          useValue: createMock<HttpService>(),
        },
      ],
    })
      .useMocker(createMock)
      .compile();

    service = await module.get<AirGatewayService>(AirGatewayService);
    httpService = await module.get(HttpService);
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

air-gateway.service.ts

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { TerminusArgs } from './dto/terminus.args';
import { AirSchedules } from './models/air-schedules.model';

@Injectable()
export class AirGatewayService {
  constructor(private readonly httpService: HttpService) {}

  public async findAll(terminusArgs: TerminusArgs): Promise<AirSchedules> {
    const { data } = await firstValueFrom(
      this.httpService
        .get<GatewayResponse<AirSchedules>>(gatewayURL.href, { headers })
        .pipe(
          catchError((error: AxiosError) => {
            throw `GatewayServiceError -> findAll: an error has occurred fetching for Gateway\n${error}`;
          })
        )
    );
  }
}

已尝试的操作:

  • 将nest、axios、jest、typescript等依赖更新至最新版本;
  • 配置babel.config.js以支持测试中的TypeScript;
  • 配置并移除过jest.config.js;
  • 尝试使用@automock/jest包,但仍出现依赖未找到错误:IdentifierNotFoundError: Missing class dependency identifier (code ER010)。

运行npx jest air-gateway.service.spec.ts的调用栈如下:

Trace: gateway
        at GatewayService.trace [as findAll] (/Users/pingwinZloty/Projects/centrus-active/apps/gateway-subgraph/src/gateway/gateway.service.ts:41:9)
        at Object.findAll (/Users/pingwinZloty/Projects/centrus-active/apps/gateway-subgraph/src/gateway/tests/gateway.service.spec.ts:140:35)
        at Promise.then.completed (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-circus/build/utils.js:298:28)
        at new Promise (<anonymous>)
        at callAsyncCircusFn (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-circus/build/utils.js:231:10)
        at _callCircusTest (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-circus/build/run.js:316:40)
        at processTicksAndRejections (node:internal/process/task_queues:95:5)
        at _runTest (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-circus/build/run.js:252:3)
        at _runTestsForDescribeBlock (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-circus/build/run.js:126:9)
        at _runTestsForDescribeBlock (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-circus/build/run.js:121:9)
        at run (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-circus/build/run.js:71:3)
        at runAndTransformResultsToJestFormat (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js:122:21)
        at jestAdapter (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js:79:19)
        at runTestInternal (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-runner/build/runTest.js:367:16)
        at runTest (/Users/pingwinZloty/Projects/centrus-active/node_modules/jest-runner/build/runTest.js:444:34)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:47:31