Reputation: 621
I want to use scrollTo() function of window object. Directly by accessing window.scrollTo(0,0), i can achieve this functionality. When i googled about using window in angular, people are creating a provider like below one:
import {InjectionToken, FactoryProvider} from '@angular/core';
export const WINDOW = new InjectionToken<Window>('window');
const windowProvider: FactoryProvider = {
provide: WINDOW,
useFactory: () => window,
};
export const WINDOW_PROVIDERS = [windowProvider];
Inside service using like the below code:
import {Injectable, Inject} from '@angular/core';
import {WINDOW} from './window.provider';
@Injectable({
providedIn: 'root',
})
export class WindowService {
constructor(@Inject(WINDOW) public window: Window) {}
}
In module
{provide: WINDOW_PROVIDERS, useValue: window},
Everything works with the above code, but while running test cases i m getting the below error. Almost half of the application test cases are failing with below error
NullInjectorError: No provider for InjectionToken window!
Default Test case for window.service
import { TestBed } from '@angular/core/testing';
import { WindowService } from './window.service';
describe('WindowService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: WindowService = TestBed.get(WindowService);
expect(service).toBeTruthy();
});
});
How to fix this??
Upvotes: 1
Views: 5617
Reputation: 1533
You need to set the following configureTestingModule
:
TestBed.configureTestingModule({
providers: [WINDOW_PROVIDERS, WindowService]
});
Upvotes: 3