Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing/mocking Window properties in Angular2 (TypeScript)

Tags:

I'm building some unit tests for a service in Angular2.

Within my Service I have the following code:

var hash: string; hash = this.window.location.hash;

However when I run a test which contains this code, it will fail.

It'd be great to utilise all the features of Window, but as I'm using PhantomJs, I don't think this is possible (I have also tried Chrome which yields the same results).

In AngularJs, I would have resorted to mocking $Window (or at least the properties in question), but as there is not a lot of documentation for Angular2 unit testing I'm not sure how to do this.

Can anyone help?

like image 927
Rhys Avatar asked Apr 12 '16 09:04

Rhys


1 Answers

In Angular 2 you can use the @Inject() function to inject the window object by naming it using a string token, like this

  constructor( @Inject('Window') private window: Window) { } 

In the @NgModule you must then provide it using the same string:

@NgModule({     declarations: [ ... ],     imports: [ ... ],     providers: [ { provide: 'Window', useValue: window } ], }) export class AppModule { } 

Then you can also mock it using the token string

beforeEach(() => {   let windowMock: Window = <any>{ };   TestBed.configureTestingModule({     providers: [       ApiUriService,       { provide: 'Window', useFactory: (() => { return windowMock; }) }     ]   }); 

This worked in Angular 2.1.1, the latest as of 2016-10-28.

Does not work with Angular 4.0.0 AOT. https://github.com/angular/angular/issues/15640

like image 178
Klas Mellbourn Avatar answered Oct 04 '22 05:10

Klas Mellbourn