尝试模拟用于单元测试的userAgent属性:
Object.defineProperty(navigator, "userAgent", {
get: function () {
return "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko"; // customized user agent
}
});
或
navigator.__defineGetter__('userAgent', function(){
return 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko'; // customized user agent
});
抛出以下错误:
TypeError: WindowActiveXObject is not a constructor
有没有其他方法可以在Jasmine中模拟userAgent?
答案 0 :(得分:0)
navigator.userAgent
是根据MDN&的唯一属性。这post。这是one way执行此操作:
var testFunc = function(name) {
return name + " " + navigator.userAgent;
}
describe('test useragent', function() {
var defaultUA = navigator.userAgent;
beforeEach(function() {
navigator.__defineGetter__('userAgent', function() {
return 'foo' // customized user agent
});
console.log("Changing UA to: " + navigator.userAgent)
});
afterEach(function() {
navigator.__defineGetter__('userAgent', function() {
return defaultUA // customized user agent
});
console.log("Resetting it to: " + navigator.userAgent)
});
it('test UA', function() {
var val = testFunc("Bruce");
console.log(val)
expect(val).toEqual("Bruce foo");
});
});