【问题标题】:Angular JS testing with external library like Google Analytics使用 Google Analytics 等外部库进行 Angular JS 测试
【发布时间】:2015-09-01 06:48:40
【问题描述】:

您如何使用外部库(例如谷歌分析事件跟踪)测试角度控制器。例如:

$scope.showVolumn  = function() {
  ga('send', {
    'hitType': 'event',          
    'eventCategory': 'Volume',   
    'eventAction': 'click',      
    'eventLabel': 'Interaction'
  });

  if($scope.native !== 'true')
    vm.showVolumnCtl = !vm.showVolumnCtl;
};

运行以为我的测试代码出现了这个错误

ReferenceError:找不到变量:ga

我认为你不能在 beforeEach 中注入 ga 对吧?

【问题讨论】:

    标签: javascript angularjs unit-testing


    【解决方案1】:

    由于ga 是一个全局变量,它附加到window 对象,因此您可以在应用程序和测试中使用$window

    只需注入$window,然后像这样调用它。

      $window.ga('send', {
        'hitType': 'event',          
        'eventCategory': 'Volume',   
        'eventAction': 'click',      
        'eventLabel': 'Interaction'
      });
    

    这将与您的工作方式完全相同。在您的测试中,只需再次注入 $window 并根据需要模拟它。

    一个简单的例子:

    beforeEach(inject(function (_$window_) {
        $window = _$window_;
        $window.ga = function(){}; //mock as you need
    }));
    

    【讨论】:

    • 很高兴它很有用。作为相关说明,在我自己在应用程序中使用 Analytics 之后,每当我有任何类型的全局变量时,我现在总是使用 $window 将其注入到我的控制器/服务/ecc 中。如您所见,它使测试变得相当简单,而且感觉更像是明确地要求依赖项,而不是默默地期待它在那里/来自天空。而且,顺便感谢“大师”,我受宠若惊。
    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 2023-02-19
    • 2016-08-14
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    相关资源
    最近更新 更多