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

Angular 18+Jest测试:注入HttpClient时无法解析DummyTest参数

问题:Angular 18 + Jest 下 HttpClient 注入失败(NG0204错误)

我正将测试从Jasmine/Karma迁移至Jest,在注入HttpClient及其测试控制器时遇到困难。按照Angular官方Http测试指南编写了如下测试代码:

import { HttpClient, provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';

describe('Testings tests', () => {
  let httpTestingController!: HttpTestingController;
  let dummyTest: DummyTest;
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [DummyTest, provideHttpClient(), provideHttpClientTesting()],
    });
    httpTestingController = TestBed.inject(HttpTestingController);
    dummyTest = TestBed.inject(DummyTest);
  });

  fit('Should request data', async () => {
    const promise = dummyTest.TestRequest();

    httpTestingController.expectOne('https://google.com').flush({});

    await promise;
  });
});

export class DummyTest {
  constructor(private httpClient: HttpClient) {}

  async TestRequest() {
    await this.httpClient.get('https://google.com');
  }
}

运行测试时出现以下错误:

NG0204: Can't resolve all parameters for DummyTest: (?).

  10 |       providers: [DummyTest, provideHttpClient(), provideHttpClientTesting()],
  11 |     });
> 12 |     httpTestingController = TestBed.inject(HttpTestingController);
     |                                     ^
  13 |     dummyTest = TestBed.inject(DummyTest);
  14 |   });

使用的是Angular 18和最新版本的Jest,已提供HttpClient和HttpClientTesting相关依赖,不清楚遗漏了什么。


解决方案
  • 错误核心原因:Angular 18默认启用Ivy严格注入模式,所有需要依赖注入的类必须显式添加@Injectable()装饰器,否则DI系统无法解析构造函数参数。
  • 修复步骤:
    1. 导入Injectable装饰器:
      import { Injectable } from '@angular/core';
      
    2. 给DummyTest类添加@Injectable()装饰器:
      @Injectable()
      export class DummyTest {
        constructor(private httpClient: HttpClient) {}
      
        async TestRequest() {
          await this.httpClient.get('https://google.com');
        }
      }
      
  • 补充说明:在旧版本Angular或非严格模式下,未添加@Injectable()的类可能被DI系统兼容解析,但Angular 18的严格模式强制要求显式声明,这也是Jest环境下触发错误的关键(Jest通常采用更严格的编译配置)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 17:37:42