2017-10-18 10 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)로 감싸는 것이 좋습니다. 네이티브 API 대신 이러한 함수를 간첩하십시오. 타이트한 기능을 사용하면 코드를 더 이식성있게 (서버 측 렌더링, 다중 브라우저 문제 등) 테스트 할 수 있습니다. 나는 항상 자스민으로 네이티브 윈도우 API를 감시하는 데 문제가있었습니다. – Sergeon

답변

2

userAgentwindow.navigator의 읽기 전용/상수 속성입니다. jasmine.createSpy은 일반적으로 메서드 및 스파이더가 아닌 속성에 스파이를 만드는 데 사용됩니다.

이제 window.navigator.userAgent = '1111';을 직접 시도해 보니 window.navigator은 내 테스트에서 쉽게 액세스 할 수 있습니다. 하지만 오류 말을 점점되었다 :

enter image description here

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

그래서 유일한 옵션은 좋은 오래된 __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

희망!