0
我需要找到改變userAgent
值的方法。我試圖spyOn
的window.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
,卻得到了我的瀏覽器真正的信息。
我建議將本機api調用包裝爲緊密函數(如http://www.adequatelygood.com/Writing-Testable-JavaScript.html),並且adn會監視這些函數而不是本地apis。依靠嚴密的功能使您的代碼更具可移植性(服務器端渲染,多瀏覽器問題等)和可測試性。我一直有問題與茉莉花間諜窗口api的間諜。 – Sergeon