2017-10-18 8 views
0

私はuserAgent値を変更する方法を見つける必要があります。私はspyOnwindow.navigator.userAgentに行きました。しかし、それは助けにはならない。Jasmine.js Testing - spy on window.navigator.userAgent

JS

@Injectable() 
export class DetectBrowserService { 
    browserIE: boolean; 
    constructor() { 
    this.browserIE = this.detectExplorer(); 
    } 

    public detectExplorer() { 
    const brows = window.navigator.userAgent; 
    const msie = brows.indexOf('MSIE '); 
    if (msie > 0) { 
     // IE 10 or older => return version number 
     return true; 
    } 
    } 
} 

スペック

it('should test window.navigator.userAgent',() => { 
    const wind = jasmine.createSpy('window.navigator.userAgent'); 
    wind.and.returnValue('1111'); 
    detectBrowserService = TestBed.get(DetectBrowserService); 
    console.log(window.navigator.userAgent); 
}); 

私は1111を期待したが、私のブラウザについての本当の情報を得ました。

+1

(http://www.adequatelygood.com/Writing-Testable-JavaScript.htmlのような)厳密な関数にネイティブのapi呼び出しをラップすることをお勧めします。厳密な関数に依存することで、コードをより移植性の高いもの(サーバー側のレンダリング、マルチブラウザの問題など)とテスト可能にすることができます。私はいつもジャスミンでネイティブウィンドウAPIをスパイする問題を抱えていました。 – Sergeon

答えて

2

userAgentは、window.navigatorの読み取り専用/定数プロパティです。 jasmine.createSpyは、一般的に、メソッドとプロパティにスパイを作成するために使用されます。

今、私はwindow.navigator.userAgent = '1111';を直接実行しました。window.navigatorは、私のテストでは簡単にアクセスできます。

[ts] Cannot assign to 'userAgent' because it is a constant or a read-only property. (property) NavigatorID.userAgent: string

enter image description here

をだから、唯一のオプションは__defineGetter__古き良きを使用していた。しかし、私はというエラーを取得しました。

it('should test window.navigator.userAgent',() => { 
    window.navigator['__defineGetter__']('userAgent', function(){ 
    return '1111' // Return whatever you want here 
    }); 
    detectBrowserService = TestBed.get(DetectBrowserService); 
    console.log(window.navigator.userAgent); 
}); 

そして、それは動作します::だから、私がここでやったことだ enter image description here

・ホープ、このことができます!