@d-cat/mocks-google-analytics-jest
v1.0.3
Published
A fully supported TypeScript mock for Google Analytics, designed for Jest.
Downloads
251
Maintainers
Readme
Getting started with @d-cat/mocks-google-analytics-jest
@d-cat/mocks-google-analytics-jest
is a Google Analytics mock designed to use with Jest. It supports both NodeJS as Web. It's tested with Jest, though it should work with any other testing library. The mock sends HTTP requests to a stubbed Google Analytics endpoint. Using AJV all inputs are validatet against the Measurement Protocol. The mock comes with built-in types.
Install
npm i -D @d-cat/mocks-google-analytics-jest
Usage
The mock returns a mock that should be assigned to a global Google Analytics variable. For example:
jest.setup.ts
Make sure you point to this file in your jest.config.js
using the setupFilesAfterEnv
prop.
// jest.setup.ts
import gaMock from '@d-cat/mocks-google-analytics-jest';
// window-or-global: https://github.com/purposeindustries/window-or-global/blob/master/lib/index.js
const root = (typeof self === 'object' && self.self === self && self) ||
(typeof global === 'object' && global.global === global && global) || this
beforeAll(() => {
// define google analytics
// at global scope
// now we can spy on it
// in our test files
root.ga = jest.fn();
});
myApp.spec.ts
// myApp.spec.ts
import gaMock from '@d-cat/mocks-google-analytics-jest';
describe('myApp', () => {
beforeEach(() => {
// spyOn ga by overriding the mock
// we use type any to ignore that
// our mock expects the types as used
// within in google analytics, but a jest mock
// expects unknown.
jest.spyOn(root, 'ga').mockImplementation(gaMock as any);
// we need this tracker to be created
// if we do not create the tracker,
// it will throw an error
// we can also define a tracker within our app
ga('create', 'UA-123456-7', 'auto', 'myTrackerName');
});
afterEach(() => {
// make sure we have a clean mock
// after each test
gaMock.mock.resetMock();
});
test('should return true', () => {
// my test
})
})
ga.mock
To use the mock in your tests, you can use the mock
object.
| parameter | type | description |
| -------------- | -------- | ---------------------------------------------- |
| gaProperties
| Array | Array with registered mocked trackers. |
| hit
| Array | Array with IGoogleAnalyticsDebugResponse objects. |
| isAsync
| Boolean | Indicates wether the Google Analytics mock is executed async. Default = false. |
| removeTracker
| Function | Removes a tracker. |
| resetMock
| Function | Resets the mock. |
| setAsync
| Function | Sets the mock to execute requests asynchronous. |
| setSync
| Function | Sets the mock to execute requests synchronous. |
ITracker
ITracker interface contains the methods as described in the official Google Analytics specs, with the exception of send
and the addition of remove
, reset
, name
and props
. It holds a state with field object key value pairs. You cannot set values that are not part of the official measurement protocol. The interface is exported in the mock.
interface ITracker {
get(fieldName: string): any;
set(fieldName: string, fieldValue: any): void;
set(fieldsObject: {}): void;
remove(name: string): void;
reset(): void;
name: string;
props: any;
}
hit
The hit array contains an array with IGoogleAnalyticsDebugResponse
's. The hit
can be used to analyze all requests that are send to Google Analytics. It uses the Measurement Protocol to validate a hit.
export interface IGoogleAnalyticsDebugResponse {
hitParsingResult: Array<{
valid: boolean;
parserMessage: Array<{
messageType: string;
description: string;
messageCode: string;
parameter: string;
}>;
hit: string;
}>;
parserMessage: Array<{
messageType: string;
description: string;
}>;
}
resetMock
The resetMock
method can be used to reset the mock.
// __tests__/myTest.spec.ts
import gaMock from '@d-cat/mocks-google-analytics-jest';
describe('MyComponent', () => {
afterAll( () => {
gaMock.mock.resetMock()
})
test('should increment', () => {
// my test
})
})
removeTracker
The removeTracker
method can be used to remove a tracker by name.
// __tests__/myTest.spec.ts
import gaMock from '@d-cat/mocks-google-analytics-jest';
describe('MyComponent', () => {
afterAll( () => {
gaMock.mock.removeTracker('ziggo')
})
test('should increment', () => {
// my test
})
})
setAsync
The setAsync
method can be used to execute Google Analytics sends asynchronous.
NOTE: Make sure you have defined a tracker before sending data to Google Analytics. If no tracker defined, it will throw an error:
undefined.send
is not a Tracker.
// __tests__/myTest.spec.ts
import gaMock from '@d-cat/mocks-google-analytics-jest';
describe('MyComponent', () => {
beforeAll( () => {
gaMock.mock.setAsync()
})
test('should increment', async () => {
const { hitParsingResult } = await ga('send', 'pageview') // IGoogleAnalyticsDebugResponse
expect(hitParsingResult[0].valid).toBe(true)
})
})
setSync
The setSync
method can be used to execute Google Analytics sends synchronous. This is the default behavior.
NOTE: Make sure you have defined a tracker before sending data to Google Analytics. If no tracker defined, it will throw an error:
undefined.send
is not a Tracker.
// __tests__/myTest.spec.ts
import gaMock from '@d-cat/mocks-google-analytics-jest';
describe('MyComponent', () => {
beforeAll( () => {
gaMock.mock.setSync()
})
test('should increment', () => {
const { hitParsingResult } = ga('send', 'pageview') // IGoogleAnalyticsDebugResponse
expect(hitParsingResult[0].valid).toBe(true)
})
})
Usage of ga
in component
When invoking ga in a component and you'll need to test if it was succesfull, the following applies:
import gaMock from '@d-cat/mocks-google-analytics-jest';
import mySyncComponent from './myComponent';
describe('MyComponent', () => {
beforeAll( () => {
global.ga = gaMock;
mySyncComponent();
})
test('should create a Google Analytics tracker', () => {
// verify if a tracker is created correctly
const tracker = gaMock.mock.gaProperties.find( tracker => tracker.name === name )
// should be defined
expect(tracker).toBeDefined()
})
test('should send a hit to Google Analytics', () => {
// in case of a pageview, the hit is the request URL. The t parameter is the hittype.
// this could be either: pageview, event, transaction, screenview, item, social, exception, timing
const { hitParsingResult } = gaMock.mock.hit.find( resp => resp[0]?.hit?.includes('t=pageview')) // IGoogleAnalyticsDebugResponse
expect(hitParsingResult[0]?.valid).toBe(true)
})
})
Known issues / Features
- there is no built-in support for screenview hittype.