2017-10-18 59 views
0

我需要找到改變userAgent值的方法。我試圖spyOnwindow.navigator.userAgent。但這沒有幫助。Jasmine.js測試 - 窺探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

我建議將本機api調用包裝爲緊密函數(如http://www.adequatelygood.com/Writing-Testable-JavaScript.html),並且adn會監視這些函數而不是本地apis。依靠嚴密的功能使您的代碼更具可移植性(服務器端渲染,多瀏覽器問題等)和可測試性。我一直有問題與茉莉花間諜窗口api的間諜。 – Sergeon

回答

2

userAgentwindow.navigator上的只讀/不變屬性。而jasmine.createSpy通常用於在方法和NOT屬性上創建間諜。

現在,我試着直接做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

希望這有助於!