问题描述
我需要找到更改userAgent
值的方法.我尝试spyOn
window.navigator.userAgent
.但这无济于事.
I need to find the way to change userAgent
value. I tried to spyOn
the window.navigator.userAgent
. But that's not helping.
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
,但是获得了有关我的浏览器的真实信息.
I was expecting 1111
, but got the real info about my browser.
推荐答案
userAgent
是window.navigator
上的只读/常量属性. jasmine.createSpy
通常用于在方法和NOT属性上创建间谍.
userAgent
is a read-only/constant property on window.navigator
. And jasmine.createSpy
is generally used to create spies on methods and NOT properties.
现在,我尝试直接执行window.navigator.userAgent = '1111';
,因为在测试中可以轻松访问window.navigator
.但我收到一个错误消息:
Now, I tried directly doing window.navigator.userAgent = '1111';
as window.navigator
would simply be accessible in my tests. But I was getting an error saying:
因此,唯一的选择是使用旧的__defineGetter__
.这就是我在这里所做的:
So the only option was to use the good old __defineGetter__
. So that's what I did here:
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);
});
它有效:
希望这会有所帮助!
这篇关于Jasmine.js测试-监视window.navigator.userAgent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!