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
相关产品推荐
相关产品推荐

