Angular 9测试报错NullInjectorError: No provider for Window的解决方案咨询
解决Angular 9测试中Window提供者缺失的问题
嘿,我懂你遇到的麻烦了!你已经按照建议正确扩展了Window的类型定义,但Angular的测试环境不会自动把全局window对象注册为依赖注入的提供者,所以才会抛出NullInjectorError: No provider for Window!这个错误。
解决方法很直接,只需在测试模块里添加Window的提供者:
你需要在TestBed.configureTestingModule的providers数组中,为Window类注册一个提供者,直接使用全局的window对象就行。修改你的spec.ts代码如下:
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AdvancedSearchComponent } from './advanced-search.component'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { RouterTestingModule } from '@angular/router/testing'; describe('AdvancedSearchComponent', () => { let component: AdvancedSearchComponent; let fixture: ComponentFixture<AdvancedSearchComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule, RouterTestingModule], declarations: [ AdvancedSearchComponent ], // 新增这一行,注册Window的提供者 providers: [{ provide: Window, useValue: window }] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AdvancedSearchComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
为什么要这么做?
Angular的依赖注入系统需要明确知道如何获取你在服务(比如AuthService、AdvancedsearchService)中注入的Window实例。开发环境里全局window是默认存在的,但测试环境是隔离的,TestBed不会自动把它纳入DI容器,所以必须手动注册。
如果需要模拟Window对象(适配特定测试场景):
要是你不想用真实的全局window,也可以提供一个模拟对象,比如:
providers: [ { provide: Window, useValue: { propName: { /* 这里放你的模拟MyInterface结构数据 */ } } } ]
这样你就能在测试里精准控制window.propName的取值,方便测试不同业务场景。
确认你的类型扩展文件(window.d.ts)配置正确、TypeScript能识别到扩展后的Window接口,再运行ng test应该就不会报错了!
内容的提问来源于stack exchange,提问作者eurodollars
相关产品推荐
相关产品推荐

