1

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??

5
  • in module providers: [windowProvider] Commented Feb 4, 2020 at 10:03
  • I assume your WINDOW_PROVIDERS is valid injection token so use it in your service as @Inject(WINDOW_PROVIDERS) public window: Window Commented Feb 4, 2020 at 10:05
  • I have added in app module providers arrays.. i have given in question also Commented Feb 4, 2020 at 10:35
  • @user2900572 Please share the test file Commented Feb 4, 2020 at 10:41
  • I have added it..its default test case.. All other test cases r also failing Commented Feb 4, 2020 at 10:49

1 Answer 1

3

You need to set the following configureTestingModule:

TestBed.configureTestingModule({
    providers: [WINDOW_PROVIDERS, WindowService]
});
Sign up to request clarification or add additional context in comments.

1 Comment

U r correct i forgot to add in providers array.. thanks Oron :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.