use*_*778 5 unit-testing jasmine karma-jasmine spyon angular
我需要找到改变userAgent价值的方法.我试过spyOn了 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
规格:
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);
});
Run Code Online (Sandbox Code Playgroud)
我期待1111,但得到了关于我的浏览器的真实信息.
Sub*_*oto 15
我使用 Jasmine apis 本身得到了一个简单的解决方案。
spyOnProperty(window.navigator, 'userAgent').and.returnValue('Mozilla');
Run Code Online (Sandbox Code Playgroud)
根据您的要求修改每个测试中的间谍。
不确定此 API 来自哪个 Jasmine 版本,但 v3.4 支持此 API
一旦您监视任何全局属性,最好清除该监视afterEach测试。
例如。
spyOnProperty(window.navigator, 'userAgent').and.returnValue('Mozilla');
Run Code Online (Sandbox Code Playgroud)
Sid*_*era 14
userAgent是一个只读/常量属性window.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
所以唯一的选择是使用好的旧__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);
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
3556 次 |
| 最近记录: |