我需要找到改变 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;
}
}
}
规范:
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
,但得到了关于我的浏览器的真实信息。
最佳答案
我使用 Jasmine api 本身得到了一个简单的解决方案。
spyOnProperty(window.navigator, 'userAgent').and.returnValue('Mozilla');
根据您的要求修改每个测试中的 spy 。
不确定这个 API 从哪个 Jasmine 版本开始出现,但是 v3.4 支持这个 API
一旦您侦测到任何全局属性,最好清除该侦测afterEach
测试。
例如。
describe('Test', function() {
const NAVIGATOR = window.navigator;
beforeEach(function() {
spyOnProperty(window.navigator, 'userAgent').and.returnValue('Mozilla');
})
afterEach(function() {
window.navigator = NAVIGATOR;
});
}
关于angular - Jasmine.js 测试 - 监视 window.navigator.userAgent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46806185/