单元测试中出现inject()必须在注入上下文调用的问题求助
解决Angular测试中
inject() must be called from an injection context错误 问题描述
测试继承AlertBase基类的AlertsComponent时,添加部分依赖服务后触发错误:
inject() must be called from an injection context
无继承关系的类测试正常,仅继承含服务构造函数的基类时出现该问题。
相关代码片段
AlertBase 基类
export abstract class AlertBase { constructor(protected alertService: IAlertService, protected alertResultService: IAlertResultService, protected paginationService: IPaginationService, protected selectedItemService: SelectedItemService) { } }
AlertsComponent 组件
@Component({ selector: 'alerts', templateUrl: './alerts.component.html', styleUrls: ['./alerts.component.less'], encapsulation: ViewEncapsulation.None, }) export class AlertsComponent extends AlertBase implements OnInit, OnDestroy { constructor( private storageService: StorageProvider, protected alertServiceProvider: AlertServiceProvider, protected alertResultProvider: AlertResultProvider, private toastNotificationService: ToastNotificationService, protected selectedItemService: SelectedItemService, protected paginationService: PaginationServiceProvider, private modalService: ModalService ) { super(alertServiceProvider, alertResultProvider, paginationService, selectedItemService); } }
测试文件
describe('AlertsComponent', () => { let component: AlertsComponent; let fixture: ComponentFixture<AlertsComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [RouterTestingModule], declarations: [AlertsComponent], providers: [ MockProvider(StorageProvider), MockProvider(AlertServiceProvider), MockProvider(AlertResultProvider), ] }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(AlertsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
问题根源
测试模块的providers中缺少组件及基类依赖的部分服务Mock,导致Angular无法在正确的注入上下文初始化所有依赖。具体缺失的服务包括:ToastNotificationService、SelectedItemService、PaginationServiceProvider、ModalService。
解决方案
在测试模块的providers数组中补充所有缺失的服务Mock:
beforeEach(async () => { await TestBed.configureTestingModule({ imports: [RouterTestingModule], declarations: [AlertsComponent], providers: [ MockProvider(StorageProvider), MockProvider(AlertServiceProvider), MockProvider(AlertResultProvider), MockProvider(ToastNotificationService), MockProvider(SelectedItemService), MockProvider(PaginationServiceProvider), MockProvider(ModalService) ] }).compileComponents(); });
确保所有通过构造函数注入的服务(包括基类和子类的)都已提供对应的Mock实例。
额外检查项
- 确认使用的
MockProvider(如ng-mocks中的工具)正确模拟了服务的接口和必要行为。 - 检查基类或组件中是否存在在构造函数/生命周期钩子之外调用
inject()的代码,这类调用必须在Angular的注入上下文内执行。
内容的提问来源于stack exchange,提问作者guiz
相关产品推荐
相关产品推荐

