使用Google Analytics等外部库进行Angular JS测试

Bru*_*uce 2 javascript unit-testing angularjs

如何使用外部库使用来测试角度控制器,例如谷歌分析事件跟踪.例如:

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

  if($scope.native !== 'true')
    vm.showVolumnCtl = !vm.showVolumnCtl;
};
Run Code Online (Sandbox Code Playgroud)

运行认为我的测试代码此错误出现

ReferenceError:找不到变量:ga

我不认为你可以在beforeEach中注入ga吗?

Nob*_*ita 5

作为ga一个全局,它附加到window对象,因此您$window在应用程序和测试中使用它们.

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

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

这将与您完全相同.在您的测试中,只需$window再次注入并根据需要进行模拟.

一个简单的例子:

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