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

Angular 12运行ng test时NullInjectorError无BaseURL provider错误如何解决

问题根因

Angular 单元测试的 TestBed 构建的是完全独立的动态测试模块,不会自动继承应用主模块 AppModule 中的依赖注入配置,你在 AppModule 中注册的 BaseURL 提供者在测试环境中不存在,因此触发 NullInjectorError。除此之外你当前的 DishService 模拟逻辑也存在兼容问题,修复 BaseURL 问题后仍会报错。

解决方案

修改你的 menu.component.spec.ts 文件,补全缺失的依赖配置、修正模拟服务的返回值即可,修改后的完整代码如下:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { MenuComponent } from './menu.component';
import { DishService } from '../services/dish.service';
import { baseURL } from '../shared/baseurl';

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

  const mockDishService = {
    getDishes: () => {
      // 用of构造Observable返回值,同时返回数组匹配组件中Dish[]类型定义
      return of([
        {
          id: '000',
          name: 'nnnnn'
        }
      ])
    }
  }

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [],
      declarations: [ MenuComponent ],
      providers: [
        { provide: DishService, useValue: mockDishService },
        // 补全BaseURL依赖注入配置
        { provide: 'BaseURL', useValue: baseURL }
      ]
    })
    .compileComponents();
  });

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
修改点说明
  • 导入了自定义的 baseURL 常量,以及rxjs的 of 操作符用来构造模拟的Observable返回值
  • 在 TestBed 的 providers 数组中添加 BaseURL 的提供者配置,和 AppModule 中的配置保持一致
  • 修正 mockDishService.getDishes 的返回值:组件中调用该方法后会执行 .subscribe(),说明原方法返回的是Observable,同时组件中接收的是菜品数组,因此用 of() 包裹数组格式的返回值匹配业务逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:36:04