Last Updated: February 25, 2016
·
1.544K
· artfulhacker

Google Analytics QUnit testing without needing ga.js

I recently needed to do some QUnit testing on some code that interacted with google analytics in javascript.

Specifically, firing some standard ga logic that read a custom var (slot 4) using this:

_gat._getTrackerByName()._getVisitorCustomVar(4);

In order to not load ga.js in the test I decided to mock these methods so that the code could be tested in QUnit, the following code will set the custom var to the string 'asu' so it can be read later in the code using the normal custom var method:

var customvar4 = undefined;

function _tracker()
{
    this._getVisitorCustomVar=_getVisitorCustomVar;
    function _getVisitorCustomVar(i)
    {
        return customvar4;
    }
}

// test the initial mocks
test( "test initial mocks", function()
{
    // setup ga mocks
    custom_gat =
    {
        _getTrackerByName: function()
        {
            return new _tracker();
        }
    }

    customvar4 = 'asu';

    function _tracker()
    {
        this._getVisitorCustomVar=_getVisitorCustomVar;
        function _getVisitorCustomVar(i)
        {
            return customvar4;
        }
    }
    (function(_gat)
    {
        equal( _gat._getTrackerByName()._getVisitorCustomVar(4), "asu", "we expect asu to be in the ga mock" );
    })(custom_gat);
});

Obviously this can be expanding on by adding more of the ga methods but this should help you get started. Also you will notice I ignore the slot number, add a switch to the method if you need specific slot data.