我需要找到改变的方法userAgent
价值。我尝试过了spyOn
the 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;
}
}
}
Spec:
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');
根据您的要求修改每个测试中的间谍。
不确定这个 API 从哪个 Jasmine 版本开始出现,但 v3.4 支持这个 API
一旦你监视了任何全球财产,最好清除该间谍afterEach
test.
Eg.
describe('Test', function() {
const NAVIGATOR = window.navigator;
beforeEach(function() {
spyOnProperty(window.navigator, 'userAgent').and.returnValue('Mozilla');
})
afterEach(function() {
window.navigator = NAVIGATOR;
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)