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

运行ng test报NullInjectorError:无RequestInterceptor提供者是什么原因?

报错原因分析
  • 核心原因是单元测试的隔离环境中,TestBed配置的测试模块没有声明RequestInterceptor的依赖提供者,Angular依赖注入容器无法找到对应服务的实例化规则,因此抛出NullInjectorError。
  • Angular单元测试的TestBed模块与业务运行时的模块完全隔离,你在AppModule等业务模块中配置的拦截器提供者不会自动同步到测试环境,必须单独声明。
  • 你已经在测试文件中导入了HTTP_INTERCEPTORS令牌,但并未将其加入测试模块的providers配置中,依赖注入流程无法完成。
修复方案

修改request-interceptor.spec.ts中的测试模块配置,在providers数组中添加RequestInterceptor的声明即可解决实例化报错:

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';

import { RequestInterceptor} from './request-interceptor';

describe('RequestInterceptorService', () => {
  
  beforeEach(() => TestBed.configureTestingModule({
    declarations: [],
    imports: [HttpClientModule, FormsModule, RouterTestingModule],
    // 新增providers配置
    providers: [
      RequestInterceptor,
      // 如果你需要测试拦截器的实际拦截逻辑,额外添加以下配置将其注册为HTTP拦截器
      {
        provide: HTTP_INTERCEPTORS,
        useClass: RequestInterceptor,
        multi: true
      }
    ]
  }));

  it('should be created', () => {
    // Angular 9+ 推荐使用TestBed.inject替代已废弃的TestBed.get
    const service: RequestInterceptor = TestBed.inject(RequestInterceptor);
    expect(service).toBeTruthy();
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:39:01