diff --git a/Gruntfile.js b/Gruntfile.js index ef050da6..bb54e1a6 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -30,9 +30,8 @@ module.exports = function(grunt) { javascripts: { src: [ 'node_modules/jquery-browser/lib/jquery.js', - 'javascripts/govuk/analytics/google-analytics-classic-tracker.js', 'javascripts/govuk/analytics/google-analytics-universal-tracker.js', - 'javascripts/govuk/analytics/tracker.js', + 'javascripts/govuk/analytics/analytics.js', 'javascripts/**/*.js' ], options: { diff --git a/docs/analytics.md b/docs/analytics.md index 8b838c3a..b4201b01 100644 --- a/docs/analytics.md +++ b/docs/analytics.md @@ -2,23 +2,20 @@ The toolkit provides an abstraction around analytics to make tracking pageviews, events and dimensions across multiple analytics providers easier. Specifically it was created to ease the migration from Google’s Classic Analytics to Universal Analytics. It includes: -* a Google Analytics classic tracker -* a Google Analytics universal tracker -* code to asynchronously load these libraries -* a generic Analytics tracker that combines these into a single API +* a Google Analytics universal tracker wrapper +* code to asynchronously load universal analytics +* a generic Analytics wrapper that allows multiple trackers to be configured * sensible defaults such as anonymising IPs -* data coercion into the format required by Google Analytics (eg a custom event value must be a number, a custom dimension’s value must be a string) +* data coercion into the format required by Google Analytics (eg a custom dimension’s value must be a string) ## Create an analytics tracker The minimum you need to use the analytics function is: 1. Include the following files from /javascripts/govuk/analytics in your project: - * google-analytics-classic-tracker.js * google-analytics-universal-tracker.js - * tracker.js + * analytics.js 2. Copy the following `init` script into your own project and replace the dummy IDs with your own (they begin with `UA-`). - * Tracker.js accepts one or both analytics tracking code, so if you are only using one type of analytics (Classic or Universal) omit the one you don't need from the instantiation of GOVUK.Tracker. (NB you will still need to include both google-analytics-classic-tracker.js and google-analytics-universal-tracker.js in your project as they are currently loaded ahead of instantiation.) * This initialisation can occur immediately as this API has no dependencies. * Load and create the analytics tracker at the earliest opportunity so that: * the time until the first pageview is tracked is kept small and pageviews aren’t missed @@ -29,7 +26,7 @@ The minimum you need to use the analytics function is: "use strict"; // Load Google Analytics libraries - GOVUK.Tracker.load(); + GOVUK.Analytics.load(); // Use document.domain in dev, preview and staging so that tracking works // Otherwise explicitly set the domain as www.gov.uk (and not gov.uk). @@ -37,9 +34,8 @@ The minimum you need to use the analytics function is: // Configure profiles and make interface public // for custom dimensions, virtual pageviews and events - GOVUK.analytics = new GOVUK.Tracker({ + GOVUK.analytics = new GOVUK.Analytics({ universalId: 'UA-XXXXXXXX-X', - classicId: 'UA-XXXXXXXX-X', cookieDomain: cookieDomain }); @@ -61,7 +57,6 @@ Once instantiated, the `GOVUK.analytics` object can be used to track virtual pag > Page tracking allows you to measure the number of views you had of a particular page on your web site. -* [Classic Analytics](https://developers.google.com/analytics/devguides/collection/gajs/asyncMigrationExamples#VirtualPageviews) * [Universal Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/pages) Argument | Description @@ -85,7 +80,6 @@ GOVUK.analytics.trackPageview('/path', 'Title'); > Event tracking allows you to measure how users interact with the content of your website. For example, you might want to measure how many times a button was pressed, or how many times a particular item was used. -* [Classic Analytics](https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide) * [Universal Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/events) Argument | Description @@ -112,45 +106,35 @@ GOVUK.analytics.trackEvent('category', 'action', { }); ``` -## Custom dimensions and custom variables +## Custom dimensions > Custom dimensions and metrics are a powerful way to send custom data to Google Analytics. Use custom dimensions and metrics to segment and measure differences between: logged in and logged out users, authors of pages, or any other business data you have on a page. -* [Classic Analytics](https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables) * [Universal Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/custom-dims-mets) -Universal custom dimensions are configured within analytics. Classic custom variables rely on the javascript to additionally pass in the name and scope of the variable. +Universal custom dimensions are configured within analytics. ### Set custom dimensions before tracking pageviews Many page level custom dimensions must be set before the initial pageview is tracked. Calls to `setDimension` should typically be made before the initial `trackPageview` is sent to analytics. -### Custom dimensions and variables must have matching indexes - -When calling `setDimension`, the first argument (`index`) becomes the index of the Universal custom dimension as well as the slot of the Classic custom variable. - Argument | Description ---------|------------ -`index` (required) | The Universal dimension’s index and and Classic variable’s slot. These must be configured to the same slot and index within analytics profiles. -`value` (required) | Value of the custom dimension/variable -`name` (required) | The name of the custom variable (classic only) -`scope` (optional) | The scope of the custom variable (classic only), defaults to a [page level scope](https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables#pagelevel) (3) if omitted +`index` (required) | The Universal dimension’s index as configured in the profile. +`value` (required) | Value of the custom dimension ```js // Set a custom dimension at index 1 with value and name -GOVUK.analytics.setDimension(1, 'value', 'name'); - -// Set a custom dimension with an alternative scope -GOVUK.analytics.setDimension(1, 'value', 'name', 2); +GOVUK.analytics.setDimension(1, 'value'); ``` ### Create custom dimension helpers -Because dimensions and variables rely on names and indexes being set correctly, it’s helpful to create methods that abstract away the details. For example: +Because dimensions rely on the correct index and that index doesn’t indicate its purpose, it’s helpful to create methods that abstract away the details. For example: ```js function setPixelDensityDimension(pixelDensity) { - GOVUK.analytics.setDimension(1, pixelDensity, 'PixelDensity', 2); + GOVUK.analytics.setDimension(1, pixelDensity); } ``` @@ -164,7 +148,7 @@ Pull `error-tracking.js` into your project, and initialise it after analytics (s ## Tracking across domains -Once a Tracker instance has been created, tracking across domains can be set up +Once an Analytics instance has been created, tracking across domains can be set up for pages like: ```js diff --git a/javascripts/govuk/analytics/analytics.js b/javascripts/govuk/analytics/analytics.js new file mode 100644 index 00000000..6c11dda3 --- /dev/null +++ b/javascripts/govuk/analytics/analytics.js @@ -0,0 +1,64 @@ +(function() { + "use strict"; + window.GOVUK = window.GOVUK || {}; + + // For usage and initialisation see: + // https://github.com/alphagov/govuk_frontend_toolkit/blob/master/docs/analytics.md#create-an-analytics-tracker + + var Analytics = function(config) { + this.trackers = []; + if (typeof config.universalId != 'undefined') { + this.trackers.push(new GOVUK.GoogleAnalyticsUniversalTracker(config.universalId, config.cookieDomain)); + } + }; + + Analytics.prototype.sendToTrackers = function(method, args) { + for (var i = 0, l = this.trackers.length; i < l; i++) { + var tracker = this.trackers[i], + fn = tracker[method]; + + if (typeof fn === "function") { + fn.apply(tracker, args); + } + } + }; + + Analytics.load = function() { + GOVUK.GoogleAnalyticsUniversalTracker.load(); + }; + + Analytics.prototype.trackPageview = function(path, title) { + this.sendToTrackers('trackPageview', arguments); + }; + + /* + https://developers.google.com/analytics/devguides/collection/analyticsjs/events + options.label – Useful for categorizing events (eg nav buttons) + options.value – Values must be non-negative. Useful to pass counts + options.nonInteraction – Prevent event from impacting bounce rate + */ + Analytics.prototype.trackEvent = function(category, action, options) { + this.sendToTrackers('trackEvent', arguments); + }; + + Analytics.prototype.trackShare = function(network) { + this.sendToTrackers('trackSocial', [network, 'share', location.pathname]); + }; + + /* + The custom dimension index must be configured within the + Universal Analytics profile + */ + Analytics.prototype.setDimension = function(index, value) { + this.sendToTrackers('setDimension', arguments); + }; + + /* + Add a beacon to track a page in another GA account on another domain. + */ + Analytics.prototype.addLinkedTrackerDomain = function(trackerId, name, domain) { + this.sendToTrackers('addLinkedTrackerDomain', arguments); + }; + + GOVUK.Analytics = Analytics; +})(); diff --git a/javascripts/govuk/analytics/google-analytics-classic-tracker.js b/javascripts/govuk/analytics/google-analytics-classic-tracker.js deleted file mode 100644 index a79628be..00000000 --- a/javascripts/govuk/analytics/google-analytics-classic-tracker.js +++ /dev/null @@ -1,130 +0,0 @@ -(function() { - "use strict"; - window.GOVUK = window.GOVUK || {}; - - var GoogleAnalyticsClassicTracker = function(id, cookieDomain) { - window._gaq = window._gaq || []; - configureProfile(id, cookieDomain); - allowCrossDomainTracking(); - anonymizeIp(); - - function configureProfile(id, cookieDomain) { - _gaq.push(['_setAccount', id]); - _gaq.push(['_setDomainName', cookieDomain]); - } - - function allowCrossDomainTracking() { - _gaq.push(['_setAllowLinker', true]); - } - - // https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApi_gat#_gat._anonymizeIp - function anonymizeIp() { - _gaq.push(['_gat._anonymizeIp']); - } - }; - - GoogleAnalyticsClassicTracker.load = function() { - var ga = document.createElement('script'), - s = document.getElementsByTagName('script')[0]; - - ga.async = true; - ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; - s.parentNode.insertBefore(ga, s); - }; - - // https://developers.google.com/analytics/devguides/collection/gajs/asyncMigrationExamples#VirtualPageviews - GoogleAnalyticsClassicTracker.prototype.trackPageview = function(path) { - var pageview = ['_trackPageview']; - - if (typeof path === "string") { - pageview.push(path); - } - - _gaq.push(pageview); - }; - - // https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide - GoogleAnalyticsClassicTracker.prototype.trackEvent = function(category, action, options) { - var value, - options = options || {}, - hasLabel = false, - hasValue = false, - evt = ["_trackEvent", category, action]; - - // Label is optional - if (typeof options.label === "string") { - hasLabel = true; - evt.push(options.label); - } - - // Value is optional, but when used must be an - // integer, otherwise the event will be invalid - // and not logged - if (options.value || options.value === 0) { - value = parseInt(options.value, 10); - if (typeof value === "number" && !isNaN(value)) { - hasValue = true; - - // Push an empty label if not set for correct final argument order - if (!hasLabel) { - evt.push(''); - } - - evt.push(value); - } - } - - // Prevents an event from affecting bounce rate - // https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide#non-interaction - if (options.nonInteraction) { - - // Push empty label/value if not already set, for correct final argument order - if (!hasValue) { - if (!hasLabel) { - evt.push(''); - } - evt.push(0); - } - - evt.push(true); - } - - _gaq.push(evt); - }; - - /* - https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiSocialTracking - network – The network on which the action occurs (e.g. Facebook, Twitter) - action – The type of action that happens (e.g. Like, Send, Tweet) - target – The text value that indicates the subject of the action - */ - GoogleAnalyticsClassicTracker.prototype.trackSocial = function(network, action, target) { - _gaq.push(['_trackSocial', network, action, target]); - }; - - // https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables - GoogleAnalyticsClassicTracker.prototype.setCustomVariable = function(index, value, name, scope) { - var PAGE_LEVEL_SCOPE = 3; - scope = scope || PAGE_LEVEL_SCOPE; - - if (typeof index !== "number") { - index = parseInt(index, 10); - } - - if (typeof scope !== "number") { - scope = parseInt(scope, 10); - } - - _gaq.push(['_setCustomVar', index, name, String(value), scope]); - }; - - // Match tracker and universal API - GoogleAnalyticsClassicTracker.prototype.setDimension = function(index, value, name, scope) { - this.setCustomVariable(index, value, name, scope); - }; - - // Match tracker and universal API - GoogleAnalyticsClassicTracker.prototype.addLinkedTrackerDomain = function() {}; - - GOVUK.GoogleAnalyticsClassicTracker = GoogleAnalyticsClassicTracker; -})(); diff --git a/javascripts/govuk/analytics/tracker.js b/javascripts/govuk/analytics/tracker.js deleted file mode 100644 index dff47c1a..00000000 --- a/javascripts/govuk/analytics/tracker.js +++ /dev/null @@ -1,68 +0,0 @@ -(function() { - "use strict"; - window.GOVUK = window.GOVUK || {}; - - // For usage and initialisation see: - // https://github.com/alphagov/govuk_frontend_toolkit/blob/master/docs/analytics.md#create-an-analytics-tracker - - var Tracker = function(config) { - this.trackers = []; - if (typeof config.universalId != 'undefined') { - this.trackers.push(new GOVUK.GoogleAnalyticsUniversalTracker(config.universalId, config.cookieDomain)); - } - if (typeof config.classicId != 'undefined') { - this.trackers.push(new GOVUK.GoogleAnalyticsClassicTracker(config.classicId, config.cookieDomain)); - } - }; - - Tracker.load = function() { - GOVUK.GoogleAnalyticsClassicTracker.load(); - GOVUK.GoogleAnalyticsUniversalTracker.load(); - }; - - Tracker.prototype.trackPageview = function(path, title) { - for (var i=0; i < this.trackers.length; i++) { - this.trackers[i].trackPageview(path, title); - } - }; - - /* - https://developers.google.com/analytics/devguides/collection/analyticsjs/events - options.label – Useful for categorizing events (eg nav buttons) - options.value – Values must be non-negative. Useful to pass counts - options.nonInteraction – Prevent event from impacting bounce rate - */ - Tracker.prototype.trackEvent = function(category, action, options) { - for (var i=0; i < this.trackers.length; i++) { - this.trackers[i].trackEvent(category, action, options); - } - }; - - Tracker.prototype.trackShare = function(network) { - var target = location.pathname; - for (var i=0; i < this.trackers.length; i++) { - this.trackers[i].trackSocial(network, 'share', target); - } - }; - - /* - Assumes that the index of the dimension is the same for both classic and universal. - Check this for your app before using this - */ - Tracker.prototype.setDimension = function(index, value, name, scope) { - for (var i=0; i < this.trackers.length; i++) { - this.trackers[i].setDimension(index, value, name, scope); - } - }; - - /* - Add a beacon to track a page in another GA account on another domain. - */ - Tracker.prototype.addLinkedTrackerDomain = function(trackerId, name, domain) { - for (var i=0; i < this.trackers.length; i++) { - this.trackers[i].addLinkedTrackerDomain(trackerId, name, domain); - } - }; - - GOVUK.Tracker = Tracker; -})(); diff --git a/spec/manifest.js b/spec/manifest.js index 0c24dc0e..fad75677 100644 --- a/spec/manifest.js +++ b/spec/manifest.js @@ -7,9 +7,8 @@ var manifest = { '../../javascripts/govuk/stick-at-top-when-scrolling.js', '../../javascripts/govuk/stop-scrolling-at-footer.js', '../../javascripts/govuk/selection-buttons.js', - '../../javascripts/govuk/analytics/google-analytics-classic-tracker.js', '../../javascripts/govuk/analytics/google-analytics-universal-tracker.js', - '../../javascripts/govuk/analytics/tracker.js' + '../../javascripts/govuk/analytics/analytics.js' ], test : [ @@ -17,8 +16,7 @@ var manifest = { '../unit/PrimaryLinksSpec.js', '../unit/StickAtTopWhenScrollingSpec.js', '../unit/SelectionButtonSpec.js', - '../unit/analytics/GoogleAnalyticsClassicTrackerSpec.js', '../unit/analytics/GoogleAnalyticsUniversalTrackerSpec.js', - '../unit/analytics/TrackerSpec.js' + '../unit/analytics/AnalyticsSpec.js' ] }; diff --git a/spec/unit/analytics/AnalyticsSpec.js b/spec/unit/analytics/AnalyticsSpec.js new file mode 100644 index 00000000..4934abcf --- /dev/null +++ b/spec/unit/analytics/AnalyticsSpec.js @@ -0,0 +1,63 @@ +describe("GOVUK.Analytics", function() { + var analytics; + + beforeEach(function() { + window.ga = function() {}; + spyOn(window, 'ga'); + this.config = { + universalId: 'universal-id', + cookieDomain: '.www.gov.uk' + }; + + analytics = new GOVUK.Analytics(this.config); + }); + + describe('when created', function() { + it('configures a universal tracker', function () { + var universalSetupArguments = window.ga.calls.allArgs(); + expect(universalSetupArguments[0]).toEqual(['create', 'universal-id', {'cookieDomain': '.www.gov.uk'}]); + }); + }); + + describe('when tracking pageviews, events and custom dimensions', function() { + it('tracks them in universal analytics', function() { + analytics.trackPageview('/path', 'Title'); + expect(window.ga.calls.mostRecent().args).toEqual(['send', 'pageview', {page: '/path', title: 'Title'}]); + + analytics.trackEvent('category', 'action'); + expect(window.ga.calls.mostRecent().args).toEqual(['send', {hitType: 'event', eventCategory: 'category', eventAction: 'action'}]); + + analytics.setDimension(1, 'value', 'name'); + expect(window.ga.calls.mostRecent().args).toEqual(['set', 'dimension1', 'value']); + }); + }); + + describe('when tracking social media shares', function() { + it('tracks in universal', function() { + analytics.trackShare('network'); + + expect(window.ga.calls.mostRecent().args).toEqual(['send', { + hitType: 'social', + socialNetwork: 'network', + socialAction: 'share', + socialTarget: jasmine.any(String) + }]); + }); + }); + + describe('when adding a linked domain', function() { + it('adds a linked domain to universal analytics', function() { + analytics.addLinkedTrackerDomain('1234', 'test', 'www.example.com'); + + var allArgs = window.ga.calls.allArgs() + expect(allArgs).toContain(['create', '1234', 'auto', {'name': 'test'}]); + expect(allArgs).toContain(['require', 'linker']); + expect(allArgs).toContain(['test.require', 'linker']); + expect(allArgs).toContain(['linker:autoLink', ['www.example.com']]); + expect(allArgs).toContain(['test.linker:autoLink', ['www.example.com']]); + expect(allArgs).toContain(['test.set', 'anonymizeIp', true]); + expect(allArgs).toContain(['test.send', 'pageview']); + }); + }); + +}); diff --git a/spec/unit/analytics/GoogleAnalyticsClassicTrackerSpec.js b/spec/unit/analytics/GoogleAnalyticsClassicTrackerSpec.js deleted file mode 100644 index 9673d5e5..00000000 --- a/spec/unit/analytics/GoogleAnalyticsClassicTrackerSpec.js +++ /dev/null @@ -1,124 +0,0 @@ -describe("GOVUK.GoogleAnalyticsClassicTracker", function() { - var classic; - - beforeEach(function() { - window._gaq = []; - classic = new GOVUK.GoogleAnalyticsClassicTracker('id', 'cookie-domain.com'); - }); - - it('can load the libraries needed to run classic Google Analytics', function() { - delete window._gaq; - $('[src*="google-analytics.com/ga.js"]').remove(); - - GOVUK.GoogleAnalyticsClassicTracker.load(); - expect($('script[async][src*="google-analytics.com/ga.js"]').length).toBe(1); - }); - - describe('when created', function() { - it('configures a Google tracker using the provided profile ID and cookie domain', function() { - expect(window._gaq[0]).toEqual(['_setAccount', 'id']); - expect(window._gaq[1]).toEqual(['_setDomainName', 'cookie-domain.com']); - }); - - it('allows cross site linking', function() { - expect(window._gaq[2]).toEqual(['_setAllowLinker', true]); - }); - - it('anonymises the IP', function() { - expect(window._gaq[3]).toEqual(['_gat._anonymizeIp']); - }); - }); - - describe('when pageviews are tracked', function() { - beforeEach(function() { - // reset queue after setup - window._gaq = []; - }); - - it('sends them to Google Analytics', function() { - classic.trackPageview(); - expect(window._gaq[0]).toEqual(['_trackPageview']); - }); - - it('can track a virtual pageview', function() { - classic.trackPageview('/nicholas-page'); - expect(window._gaq[0]).toEqual(['_trackPageview', '/nicholas-page']); - }); - }); - - describe('when events are tracked', function() { - beforeEach(function() { - // reset queue after setup - window._gaq = []; - }); - - it('sends them to Google Analytics', function() { - classic.trackEvent('category', 'action', {label: 'label'}); - expect(window._gaq[0]).toEqual(['_trackEvent', 'category', 'action', 'label']); - }); - - it('the label is optional', function() { - classic.trackEvent('category', 'action'); - expect(window._gaq[0]).toEqual(['_trackEvent', 'category', 'action']); - }); - - it('a value can be tracked if the label is omitted', function() { - classic.trackEvent('category', 'action', {value: 10}); - expect(window._gaq[0]).toEqual(['_trackEvent', 'category', 'action', '', 10]); - }); - - it('only sends values if they are parseable as numbers', function() { - classic.trackEvent('category', 'action', {label: 'label', value: '10'}); - expect(window._gaq[0]).toEqual(['_trackEvent', 'category', 'action', 'label', 10]); - - classic.trackEvent('category', 'action', {label: 'label', value: 10}); - expect(window._gaq[1]).toEqual(['_trackEvent', 'category', 'action', 'label', 10]); - - classic.trackEvent('category', 'action', {label: 'label', value: 'not a number'}); - expect(window._gaq[2]).toEqual(['_trackEvent', 'category', 'action', 'label']); - }); - - it('can mark an event as non interactive', function() { - classic.trackEvent('category', 'action', {label: 'label', value: 1, nonInteraction: true}); - expect(window._gaq[0]).toEqual(['_trackEvent', 'category', 'action', 'label', 1, true]); - }); - - it('can mark an event as non interactive without a value', function() { - classic.trackEvent('category', 'action', {label: 'label', nonInteraction: true}); - expect(window._gaq[0]).toEqual(['_trackEvent', 'category', 'action', 'label', 0, true]); - }); - - it('can mark an event as non interactive without a label or value', function() { - classic.trackEvent('category', 'action', {nonInteraction: true}); - expect(window._gaq[0]).toEqual(['_trackEvent', 'category', 'action', '', 0, true]); - }); - }); - - describe('when social events are tracked', function() { - beforeEach(function() { - window._gaq = []; - }); - - it('sends them to Google Analytics', function() { - classic.trackSocial('network', 'action', 'target'); - expect(window._gaq[0]).toEqual(['_trackSocial', 'network', 'action', 'target']); - }); - }); - - describe('when setting a custom variable', function() { - beforeEach(function() { - // reset queue after setup - window._gaq = []; - }); - - it('sends the variable to Google Analytics', function() { - classic.setCustomVariable(1, 'value', 'name', 10); - expect(window._gaq[0]).toEqual(['_setCustomVar', 1, 'name', 'value', 10]); - }); - - it('coerces the value to a string', function() { - classic.setCustomVariable(1, 100, 'name', 10); - expect(window._gaq[0]).toEqual(['_setCustomVar', 1, 'name', '100', 10]); - }); - }); -}); diff --git a/spec/unit/analytics/TrackerSpec.js b/spec/unit/analytics/TrackerSpec.js deleted file mode 100644 index e51f25b7..00000000 --- a/spec/unit/analytics/TrackerSpec.js +++ /dev/null @@ -1,115 +0,0 @@ -describe("GOVUK.Tracker", function() { - var tracker; - - beforeEach(function() { - window._gaq = []; - window.ga = function() {}; - spyOn(window, 'ga'); - this.config = { - universalId: 'universal-id', - classicId: 'classic-id', - cookieDomain: '.www.gov.uk' - }; - }); - - describe('when created', function() { - var universalSetupArguments; - - beforeEach(function () { - tracker = new GOVUK.Tracker(this.config); - universalSetupArguments = window.ga.calls.allArgs(); - }); - - it('configures classic and universal trackers', function () { - expect(window._gaq[0]).toEqual(['_setAccount', 'classic-id']); - expect(window._gaq[1]).toEqual(['_setDomainName', '.www.gov.uk']); - expect(universalSetupArguments[0]).toEqual(['create', 'universal-id', {'cookieDomain': '.www.gov.uk'}]); - }); - - }); - - describe('when created with only universal analytics', function() { - var universalSetupArguments; - - beforeEach(function () { - }); - - it ('doesn\'t require both trackers to be present', function() { - universalOnlyConfig = { universalId: 'universal-id', - cookieDomain: '.www.gov.uk' - }; - - var tracker = new GOVUK.Tracker(universalOnlyConfig); - - universalSetupArguments = window.ga.calls.allArgs(); - expect(typeof(window._gaq[0])).toEqual('undefined'); - expect(universalSetupArguments[0]).toEqual(['create', 'universal-id', {'cookieDomain': '.www.gov.uk'}]); - }); - }); - - describe('when tracking pageviews, events and custom dimensions', function() { - - beforeEach(function() { - tracker = new GOVUK.Tracker(this.config); - }); - - it('tracks in both classic and universal', function() { - window._gaq = []; - tracker.trackPageview('/path', 'Title'); - expect(window._gaq[0]).toEqual(['_trackPageview', '/path']); - expect(window.ga.calls.mostRecent().args).toEqual(['send', 'pageview', {page: '/path', title: 'Title'}]); - - window._gaq = []; - tracker.trackEvent('category', 'action'); - expect(window._gaq[0]).toEqual(['_trackEvent', 'category', 'action']); - expect(window.ga.calls.mostRecent().args).toEqual(['send', {hitType: 'event', eventCategory: 'category', eventAction: 'action'}]); - - window._gaq = []; - tracker.setDimension(1, 'value', 'name'); - expect(window._gaq[0]).toEqual(['_setCustomVar', 1, 'name', 'value', 3]); - expect(window.ga.calls.mostRecent().args).toEqual(['set', 'dimension1', 'value']); - }); - }); - - describe('when tracking social media shares', function() { - - beforeEach(function() { - tracker = new GOVUK.Tracker(this.config); - }); - - it('tracks in both classic and universal', function() { - window._gaq = []; - tracker.trackShare('network'); - - expect(window._gaq[0]).toEqual(['_trackSocial', 'network', 'share', jasmine.any(String)]); - expect(window.ga.calls.mostRecent().args).toEqual(['send', { - hitType: 'social', - socialNetwork: 'network', - socialAction: 'share', - socialTarget: jasmine.any(String) - }]); - }); - }); - - describe('when adding a linked domain', function() { - beforeEach(function() { - tracker = new GOVUK.Tracker(this.config); - }); - - it('adds a linked domain to universal only', function() { - window._gaq = []; - tracker.addLinkedTrackerDomain('1234', 'test', 'www.example.com'); - - expect(window._gaq).toEqual([]); - var allArgs = window.ga.calls.allArgs() - expect(allArgs).toContain(['create', '1234', 'auto', {'name': 'test'}]); - expect(allArgs).toContain(['require', 'linker']); - expect(allArgs).toContain(['test.require', 'linker']); - expect(allArgs).toContain(['linker:autoLink', ['www.example.com']]); - expect(allArgs).toContain(['test.linker:autoLink', ['www.example.com']]); - expect(allArgs).toContain(['test.set', 'anonymizeIp', true]); - expect(allArgs).toContain(['test.send', 'pageview']); - }); - }); - -});