Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Google Analytics function call ga()

I have a service MyService with a function using the ga() event tracking call which I want to test:

angular.module('myModule').factory('MyService', [function() {

    var myFunc = function() {
        ga('send', 'event', 'bla');
        // do some stuff
    }

    return {
        myFunc: myFunc
    }
]);

My spec file looks like this:

describe('The MyService', function () {

    var MyService,
        ga;

    beforeEach(function () {
        module('myModule');
        ga = function() {};
    });

    beforeEach(inject(function (_MyService_) {
        MyService = _MyService_;
    }));

    it('should do some stuff', function () {
        MyService.myFunc();
        // testing function
    });
});

Running my tests always gives me:

ReferenceError: Can't find variable: ga

like image 308
DonJuwe Avatar asked Apr 22 '16 12:04

DonJuwe


2 Answers

The problem is global scope of ga.

The ga variable that you create inside your tests has a local scope and will not be visible to your own service.

By using a global variable (ga) you have made unit testing difficult.

The current option would be to either create a angular service to wrap gaand use that everywhere else. Such service can be mocked too.

The other option is to override the global ga. But this will have side effects.

window.ga=function() {}

like image 56
Chandermani Avatar answered Sep 28 '22 02:09

Chandermani


After trying different solution I finally fixed with below code.

beforeAll( ()=> {
    // (<any>window).gtag=function() {} // if using gtag
    (<any>window).ga=function() {}
})
like image 34
Shabbir Dhangot Avatar answered Sep 28 '22 00:09

Shabbir Dhangot