Bill
Bill

Reputation: 19298

Angular JS testing with external library like Google Analytics

How do you testing angular controller with external library usage such as google analytic event tracking. For example:

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

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

Run thought my test code this error appeard

ReferenceError: Can't find variable: ga

I don't think you can inject ga in the beforeEach right?

Upvotes: 2

Views: 643

Answers (1)

Aurelio
Aurelio

Reputation: 25792

As ga is a global, it's attached to the window object, so you use $window both in your app and in your tests.

Just inject $window and then call it like so.

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

This will work exactly the same as you have. In your tests just inject $window again and mock it as you like.

A quick example:

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

Upvotes: 5

Related Questions