blunatic
blunatic

Reputation: 335

Error in Jasmine test from Google Analytics in Angular app

I'm working on some unit tests for my Angular app using Karma + Jasmine in a Grunt build. I have the following run block code that sets up Google Analytics:

run.$inject = ['$rootScope', '$state', '$location', '$auth', '$window', 'AUTH_EVENTS', 'AuthService', 'Permission'];

function run($rootScope, $state, $location, $auth, $window, AUTH_EVENTS, AuthService, Permission) {
    // Initialize Google Analytics for tracking page views w/ ui-router state changes
    $window.ga('create', 'UA-XXXXXXXX-X', 'auto');

When running grunt test I'm getting the following error from the $window.ga(.. line:

TypeError: 'undefined' is not a function (evaluating '$window.ga('create', 'UA-XXXXXXX-X', 'auto')')

If I remove the line completely, the error is gone and the Jasmine tests continue on through just fine. Any ideas?

Upvotes: 3

Views: 2137

Answers (1)

akniazi
akniazi

Reputation: 732

We provide all the JavaScript files which are used by Jasmine in karma.conf.js file to load dependencies.You get undefined because Jasmine cannot find ga function which is defined in analytics.js. To avoid this error you may want to mock it like below

var $rootScope, $window;

beforeEach(inject(function(_$rootScope_, _$window_) {
    $rootScope = _$rootScope_;
    $window = _$window_;
    $window.ga = function(){};
}));

Upvotes: 7

Related Questions