2

I have started to write my tests for an Angular 9 app. I followed the advice given by Jeff Camera about half way down this post:

How do you explicitly set a new property on `window` in TypeScript?

If you need to extend the window object with a custom type that requires the use of import you can use the following method:

window.d.ts

import MyInterface from './MyInterface';

declare global { interface Window { propName: MyInterface } }

I am not getting this error when I run ng test.

NullInjectorError: R3InjectorError(DynamicTestModule)[AdvancedsearchService -> AuthService -> Window -> Window]: 
  NullInjectorError: No provider for Window!

Here is my spec.ts for the component in question

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();
  });
});

I am not sure where I am supposed to add the provider for Window.

daan.desmedt
  • 3,752
  • 1
  • 19
  • 33
eurodollars
  • 47
  • 1
  • 8

1 Answers1

3

Are you sure you added Window to your module provider ? This error says you have used window but it is not defined in your module.ts

Example:

providers: [ Window ],

it should be the same for AdvancedsearchService AuthService

Zoubeir
  • 86
  • 3
  • I think you are correct. I added some code to the providers in the TestBed config. beforeEach(async(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule, RouterTestingModule], declarations: [ AdvancedSearchComponent ], providers: [{ provide: Window, useValue: window }] }) .compileComponents(); })); I am not getting some errors related to "TypeError: Cannot read property 'settings' of undefined" but I believe that is out of scope for this question. Thank you – eurodollars Jan 19 '21 at 16:32