2016-07-22 5 views
4
私はこの機能を持っている

にwindow.location.href呼び出す関数をする:私は外部のURLにナビゲートするwindow.location.hrefを使用私がテストする必要がどのようにユニットテストAngular2

login(): void { 
    this.userService.setSessionAndDateOnlogin(); 
    this.loginService.getLogin() 
     .subscribe(
     octopusUrl => window.location.href = octopusUrl); 
    } 

これは私のテストです:私はこのテストを実行すると

it('login function should call the setSessionAndDateOnLogin function from the userservice and\ 
    subscribe to the getLogin function of the loginService.', 
    fakeAsync(
     inject(
     [LoginComponent, LoginService, UserService], 
     (loginComponent: LoginComponent, loginService: LoginService, userService: UserService) => { 
      spyOn(userService, 'setSessionAndDateOnlogin'); 
      loginComponent.login(); 
      expect(userService.setSessionAndDateOnlogin).toHaveBeenCalled(); 
     }) 
    ) 
); 

、私は次のエラーを取得する:

Some of your tests did a full page reload!

だから私は、ウィンドウオブジェクトを模擬してみました:

import { window } from '@angular/platform-browser/src/facade/browser'; 
... 
class MockWindow { 
    location: { 
    href: '' 
    }; 
} 
... 
beforeEach(() => addProviders([ 
    ... 
    { provide: window, useClass: MockWindow } 
    ])); 

これは何も変更されず、エラーが残ります。

誰にもこの問題の解決策がありますか?

答えて

3

ウィンドウはインターフェイスであり、注入できません。あなたはテスト

describe('SomeServiceWithWindowDependency',() => { 
    beforeEach(() => { 
    let mockWindow: any = { 
     location: { 
     hostname: '' 
     } 
    }; 
    TestBed.configureTestingModule({ 
     providers: [ 
     {provide: WindowToken, useValue: mockWindow}, 
     {provide: SomeServiceWithWindowDependencyToken, useClass: SomeServiceWithWindowDependency} 
     ] 
    }); 
    }); 
    it('should do something', inject([SomeServiceWithWindowDependencyToken, WindowToken], (tested: SomeServiceWithWindowDependency, window: Window) => { 
    window.location.hostname = 'localhost'; 
    expect(tested.someMethod()).toBe('result'); 
    })); 
}); 

に続いてOpaqueToken

import {Injectable, OpaqueToken, Inject} from '@angular/core'; 

export const WindowToken = new OpaqueToken('Window'); 
export const SomeServiceWithWindowDependencyToken = new OpaqueToken('SomeServiceWithWindowDependency'); 

export function _window(): Window { 
    return window; 
} 


export class SomeServiceWithWindowDependency { 
    private window: Window; 

    constructor(@Inject(WindowToken) window: Window) { 
    this.window = window; 
    } 
} 

を使用して、実際のウィンドウオブジェクトに

@NgModule({ 
declarations: [ 
    ... 
    ], 
    imports: [ 
    ... 
    ], 
    providers: [ 
    ... 
    {provide: WindowToken, useFactory: _window}, 
    ], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { 
} 
を使用するアプリケーションモジュールを構成するために忘れてはなりません
関連する問題