Unit Testing/mocking Window properties in Angular2 (TypeScript)

前端 未结 4 1679
醉酒成梦
醉酒成梦 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: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 =  { location:  { hash: 'WAOW-MOCK-HASH' }};
        provide(Window, {useValue: myMockWindow})
    ]);
    
    it('should do the things', () => {
        let mockHash = myMockWindow.location.hash;
        //...
    });
    

提交回复
热议问题