TypeError: WindowActiveXObject is not a constructor

TypeError: WindowActiveXObject is not a constructor

尝试模拟 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 吗?

  • navigator.userAgent 根据 MDN & this post.
  • 是只读属性
  • 因此您将无法监视它,因为您会收到一条错误消息,指出未找到可写方法。
  • 但是您可以覆盖 userAgent 并相应地从茉莉花单元测试中的 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");
  });
});