Take the first step towards building your winning team

Click now to get your FREE copy of our Agile Transformation starter guide.
Email address
First Name
Last Name
Secure and Spam free...

Automating Google Analytics Events Tracking

Automating Google Analytics Events Tracking

The evolution of the software world is quickly rendering manual processes not only obsolete but particularly annoying for the few who have not yet figured out how to transition.

Recently, a client reached out to my team, frustrated about the tedious task of having to manually track the performance of their custom google analytics events. They had tried a few methods, all manual and all of which proved to be just as time-consuming and inefficient.

The solution was clear- AUTOMATION. Using Nightwatch, my team was able to create an automated process to track these events, thereby alleviating the pressure on their team and saving them both hours and dollars.

In this article, I’m going to walk you through the steps for automating Google Analytics Event Tracking. Before doing that, I want to make sure there is a clear understanding of two elements: events and the datalayer.

Events can be considered as the interactions that users have with the content on your page. When users click on a button to sign up for newsletters, download content from your site or even visits your page, those can all be tracked using google analytics.

In order to track events, Google Analytics uses a global JavaScript object called the ‘dataLayer’. This object holds all the relevant data related to your events. It can also store variables if you need to access those as well. Using this object is not a must, but events cannot be utilized without the object and it is best to use the functions provided by Google alongside a data layer. This will make it much easier for the data in the dataLayer to be referenced.

Finally, here’s a demonstration of how the workings of this object can be achieved using Nightwatch to test the Google’s Analytics website.

Automation Using Nightwatch

let browsePage = {};

export default {
  beforeEach (browser) {
    browsePage = browser.page.analytics();
    browser.deleteCookie(() => {
      browser.url('https://analytics.google.com/analytics/web/provision/?authuser=0#provision/SignUp/');
    });
  },


  'Verify that the display right inview ads are displayed - [1]': browser => {
    browsePage.googleSignIn().then( () => {
        let gEvent = {"event":"gtm.historyChange"}
        browser.waitForElementVisible('#ID-provisionPageContainer', 10000);
        browser.execute(()=>{
             return window.dataLayer;
        }, [], function (response) {
            let originalDataLayerLength = response.value.length;
            browsePage.trackingAnalytics('input[class^="ACTION-signup TARGET-user_GACk _GAokb"]', browser.waitedClick, originalDataLayerLength, gEvent)
                      .then((result) => {
                          browser.log(result);
                            if(result.length === false){
                                browser.verify.ok(false, "G Event not found!");
                            } else {
                                browser.verify.ok(true, "G Event found");
                            }
                      })
        });
    });
  },

  after (browser) {
    browser.end();
  }
};

As seen in the test file above, declare and initialize the browsePage object in order to easily access the methods of the page object. This will offer cleaner code as well as better readability.

  • Declare and initialize the gEvent object with the event entry you will be looking for. This object can contain more than one key:value pair.
  • Nightwatch will launch a new instance of the browser, therefore, a Google sign-in will be required.
  • After that, there will be a wait for the page to load and this is done by checking for the container that holds all the data.
  • If that is successful, there will be a browser.execute function in order to attain the current dataLayer upon initial page load.
  • Once that is done, the original length of the dataLayer will be stored in order to determine if the dataLayer increased in size when the event was triggered. If the length did not increase, then there is no need to do additional checks and this will cut down on the time taken to complete the test.
  • The tracking analytics function will then be executed. This will trigger the event and track the dataLayer to see if the event has been added to it. The browser.waitedClick is a custom command that will be used to wait for the element to be visible before clicking.
     trackingAnalytics(element, eventFunction, originalDataLayerLength, gEvent) { 
    return new Promise((resolve) => { let status = false;
    
               this.triggerEvent(element, eventFunction).then((res) => {
                    this.waitForElementVisible('#ID-createAccount', 5000);
    
                    this.api.execute(() => {
                        return window.dataLayer;
                    }, [], function (response) {
                        this.log(response);
                        let newDataLayerLength = response.value.length;
    
                        let keys = Object.keys(gEvent);
    
                        if (newDataLayerLength > originalDataLayerLength) {
                            response.value.forEach(respObj => {
                                for (let key of keys) {
                                    if (Object.keys(respObj).includes(key)) {
                                        if (respObj[key] === gEvent[key]) {
                                            this.log('yes')
                                            status = true;
                                        } 
                                    }
                                }
                            });
                        }
                    });
                    resolve(status);
                });
        });
    }
    
  • Once the container is visible, the triggerEvent function will be executed. This will run the custom command to trigger the event.
     
    triggerEvent(element, eventFunction) { 
         return new Promise((resolve) => { 
              this.api.perform(async done => { 
                   try { 
                        eventFunction(element, result => { 
                             this.log('done'); 
                             resolve('yes'); done(); });
                   } catch (err) {
                        this.log(err)
                   }
              });
         });
    },
    
  • The new length of the dataLayer will then be ascertained to determine if the event was triggered.
  • The keys will also be obtained from the gEvent to determine if the dataLayer does in fact hold that event
  • Once it is found that the length has increased, each object in the dataLayer will then used to compare with the gEvent passed to the function. Once the object is found, the status is turned to true and resolved

Once the result is received, the test will verify if the event was found or not.

Note that this tutorial is written to test for one event but can be modified to check for several events in the dataLayer.

Click here to get more information on how you can use automation to optimize your google events tracking and other processes and improve team efficiency.

Khadijah is a QA Consultant and full-stack developer at QualityWorks Consulting Group. When she's not busy being a front-end Guru, she spends her time mastering the art of playing video games.

This entry has 0 replies

Comments open

Leave a reply