Mocking Google Analytics API

Viewed 646

I would like to create a Web Application that uses data from the google analytics API. The problem with this is, that in order to use google analytics, the app needs to be online and have users visiting it.
So is there a way to mock the google analytics API, or generate some fake data for development and testing purposes (ie it lets me set pageviews and other things manually)?

3 Answers

You can use some online api mocker to mock the apis. Like: https://themockapis.in/ You can define custom path and custom response.

Depending on your environment you can use a library like Jest to mock your API calls and have those calls return mock data.

I did this recently on a Typescript project with Jest. First thing you will need to do is auto mock all of the API calls that might look something like this:

export const analyticsMock = {
    Management: {
        Profiles: {
            insert: jest.fn(),
            list: jest.fn()
        },
        ProfileFilterLinks: {
            /*
            *this is a mocked endpoint with a mock return living in a 
            different file to keep things clean 
            */
            insert: jest.fn().mockReturnValue(profileFilterInsertResponseMock),
            list: jest.fn()
        },
        Goals: {
            insert: jest.fn().mockReturnValue(goalInsertResponseMock)
        },
        Filters: {
            insert: jest.fn().mockReturnValue({id: "33333333"})
        }
    }
}

Here's an example of what the mocked function might return depending on the endpoint:

export const profileListMock = {
    "kind": "analytics#profiles",
    items: [
        {
            accountId: "1123123",
            id: "123123123",
            name: "Testing 1 DI Goals"
        },
        {
            accountId: "1123123",
            id: "654654654",
            name: "Testing 2 Arnold Goals"
        }
    ]
}

You will just have to make sure in your test file you also include something like this:

  beforeEach(() =>{
      global.Analytics = analyticsMock as unknown as GoogleAppsScript.Analytics
  })

This allows me to tell the program it needs to extends my mock (analyticsMock) to global.Analytics which allows my mocked endpoints to work within test files.

Related