Unit Testing/mocking Window properties in Angular2 (TypeScript)

前端 未结 4 1678
醉酒成梦
醉酒成梦 2020-12-17 09:23

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.h

相关标签:
4条回答
  • 2020-12-17 09:30

    I really don't get why nobody provided the easiest solution which is the recommended way by the Angular-Team to test a service as you can see here. You even don't have to deal with the TestBed stuff at all in most of the cases.

    Futhermore, you can use this approach for components and directives as well. In that case, you won't create a component-instance but a class-instance. This means, you don't have to deal with the child-components used within the components template as well.

    Assuming you are able to inject Window into your constructor

    constructor(@Inject(WINDOW_TOKEN) private _window: Window) {}
    

    Just do the following in your .spec file:

    describe('YourService', () => {
      let service: YourService;
      
      beforeEach(() => {
        service = new YourService(
          {
            location: {hash: 'YourHash'} as any,
            ...
          } as any,
          ...
        );
      });
    }
    

    I don't care about other properties, therefore I usually add a type cast to any. Feel free to include all other properties as well and type appropriately.

    In case you need different values on the mocked properties you can simply spy on them and change the value using returnValue of jasmine:

    const spy: any = spyOn((service as any)._window, 'location').and.returnValue({hash: 'AnotherHash'});
    

    or

    const spy: any = spyOn((service as any)._window.location, 'hash').and.returnValue('AnotherHash');
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-17 09:31

    As @estus mentioned in the comment, you'd be better getting the hash from the Router. But to answer your question directly, you need to inject window into the place you're using it, so that during testing you can mock it.

    First, register window with the angular2 provider - probably somewhere global if you use this all over the place:

    import { provide } from '@angular/core';
    provide(Window, { useValue: window });
    

    This tells angular when the dependency injection asks for the type Window, it should return the global window.

    Now, in the place you're using it, you inject this into your class instead of using the global directly:

    import { Component } from '@angular/core';
    
    @Component({ ... })
    export default class MyCoolComponent {
        constructor (
            window: Window
        ) {}
    
        public myCoolFunction () {
            let hash: string;
            hash = this.window.location.hash;
        }
    }
    

    Now you're ready to mock that value in your test.

    import {
        beforeEach,
        beforeEachProviders,
        describe,
        expect,
        it,
        inject,
        injectAsync
    } from 'angular2/testing';
    
    let myMockWindow: Window;
    beforeEachProviders(() => [
        //Probably mock your thing a bit better than this..
        myMockWindow = <any> { location: <any> { hash: 'WAOW-MOCK-HASH' }};
        provide(Window, {useValue: myMockWindow})
    ]);
    
    it('should do the things', () => {
        let mockHash = myMockWindow.location.hash;
        //...
    });
    
    0 讨论(0)
  • 2020-12-17 09:31

    After RC4 method provide() its depracated, so the way to handle this after RC4 is:

      let myMockWindow: Window;
    
      beforeEach(() => {
        myMockWindow = <any> { location: <any> {hash: 'WAOW-MOCK-HASH'}};
        addProviders([SomeService, {provide: Window, useValue: myMockWindow}]);
      });
    

    It take me a while to figure it out, how it works.

    0 讨论(0)
提交回复
热议问题