TypeError:WindowActiveXObject不是构造函数

时间:2016-11-29 10:53:40

标签: javascript unit-testing jasmine user-agent

尝试模拟用于单元测试的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?

1 个答案:

答案 0 :(得分:0)

  • navigator.userAgent是根据MDN&的唯一属性。这post
  • 因此,您将无法监视它,因为您将收到一条错误消息,指出未找到可写方法。
  • 但是,您可以覆盖userAgent并相应地从jasmine单元测试中的before & after blocks进行模拟。

这是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");
  });
});