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

运行ng test遇StaticInjectorError:AuthService无提供者问题求助

Angular测试报错:NullInjectorError: No provider for AuthService!

兄弟,你这问题我太熟了!运行ng test时抛出的这个错误,核心原因很明确:Angular的测试模块里没有正确提供AuthService这个依赖,而且你写的AuthService测试代码还踩了一个典型的坑——把服务当成组件来处理了!

先看你的测试代码问题:
AuthService是Angular服务(Service),不是组件(Component),所以:

  • 不能把它放在declarations数组里(declarations是用来放组件、指令、管道的)
  • 也不能用TestBed.createComponent()来创建服务实例(这个方法是给组件用的)

修正后的AuthService测试代码

你应该用providers数组注册服务,再通过TestBed.inject()获取实例:

describe('Service: Auth', () => {
  let authService: AuthService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      // 服务要放在providers数组中声明
      providers: [AuthService]
    });
    // 使用TestBed.inject()获取服务实例
    authService = TestBed.inject(AuthService);
  });

  // 示例测试用例:验证服务能被创建
  it('should be created', () => {
    expect(authService).toBeTruthy();
  });
});

为什么NotificationsComponent也报错?

因为你的NotificationsComponent依赖了AuthService,当你测试这个组件时,对应的测试模块里同样没有提供AuthService,所以Angular找不到这个依赖,就抛出了NullInjectorError。

如果要测试NotificationsComponent,你需要在它的测试模块里把AuthService加入providers数组,或者用Mock服务替代(避免依赖真实服务的复杂逻辑),示例如下:

describe('NotificationsComponent', () => {
  let component: NotificationsComponent;
  let fixture: ComponentFixture<NotificationsComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [NotificationsComponent],
      // 在这里提供AuthService,或者Mock版本
      providers: [AuthService]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(NotificationsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:24:58