Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9 test error NullInjectorError: No provider for Window

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.

like image 438
eurodollars Avatar asked Oct 19 '25 11:10

eurodollars


1 Answers

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

like image 193
Zoubeir Avatar answered Oct 21 '25 01:10

Zoubeir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!