Angular 9测试错误:NullInjectorError:没有提供Window的提供者

4
我已经开始为一个Angular 9 应用编写测试。我遵循了Jeff Camera在这篇文章中给出的建议,大约在文章的一半处:
如何在TypeScript中显式设置`window`上的新属性?
如果您需要使用import扩展具有自定义类型的window对象,可以使用以下方法:
window.d.ts
import MyInterface from './MyInterface';
declare global { interface Window { propName: MyInterface } }
当我运行ng test时,我没有收到此错误。
NullInjectorError: R3InjectorError(DynamicTestModule)[AdvancedsearchService -> AuthService -> Window -> Window]: 
  NullInjectorError: No provider for 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 ]
    })
    .compileComponents();
  }));

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

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

我不确定在哪里应该添加Window的提供者。
1个回答

4

您确定已将 Window 添加到您的模块提供程序中吗? 该错误指出,您在模块 .ts 文件中使用了 window,但未对其进行定义。

示例:

providers: [ Window ],

高级搜索服务(AdvancedsearchService)和认证服务(AuthService)也应该是相同的。


我认为你是正确的。我在TestBed配置中的providers中添加了一些代码。 beforeEach(async(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule, RouterTestingModule], declarations: [ AdvancedSearchComponent ], providers: [{ provide: Window, useValue: window }] }) .compileComponents(); }));我没有遇到与"TypeError: Cannot read property 'settings' of undefined"相关的错误,但我相信这超出了这个问题的范围。谢谢。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接