Skip to content

Commit

Permalink
feat: Add google analytics (ga) adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
44px committed Nov 5, 2018
1 parent 87e36f7 commit daee27f
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 1 deletion.
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@
},
"testEnvironment": "jsdom",
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"/node_modules/",
"/dist/"
],
"moduleFileExtensions": [
"ts",
"tsx",
Expand All @@ -69,7 +73,7 @@
},
"collectCoverage": true,
"collectCoverageFrom": [
"src/*.{js,ts}"
"src/**.{js,ts}"
]
},
"prettier": {
Expand Down
44 changes: 44 additions & 0 deletions src/adapters/google-ga.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { googleGA } from './google-ga';

declare global {
namespace NodeJS {
interface Global {
ga?: Function;
}
}
}

describe('googleGA', () => {
it('does nothing if Google Analytics function not found', () => {
expect(() => {
googleGA('test');
}).not.toThrow();
});

it('maps event only', () => {
global.ga = jest.fn();

googleGA('testEvent');

expect(global.ga).toBeCalledWith('send', 'event', undefined, 'testEvent', undefined, undefined);
});

it('maps event and its properties', () => {
global.ga = jest.fn();

googleGA('testEvent', {
category: 'testCategory',
label: 'testLabel',
value: 'testValue',
});

expect(global.ga).toBeCalledWith(
'send',
'event',
'testCategory',
'testEvent',
'testLabel',
'testValue',
);
});
});
31 changes: 31 additions & 0 deletions src/adapters/google-ga.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { EventProperties, EventTracker } from '../wrapped-analytics';

// ga function signature:
// ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);
// see https://developers.google.com/analytics/devguides/collection/analyticsjs/events#implementation
interface GA {
(
method: string,
type: string,
eventCategory?: string,
eventAction?: string,
eventLabel?: string,
fieldsObject?: any,
): void;
}

declare global {
interface Window {
ga?: GA;
}
}

export const googleGA: EventTracker = (event: string, eventProperties?: EventProperties): void => {
const ga = window.ga;
if (!ga) {
return;
}

const { category, label, value } = eventProperties || ({} as EventProperties);
ga('send', 'event', category, event, label, value);
};

0 comments on commit daee27f

Please sign in to comment.