Unit testing React Google Analytics (react-ga) with Jest

Published on 16 November 2019

This article describes how to unit test a React component using react-ga, including globally setting up the Jest config to initialize test mode each time.

Initializing ReactGA

In your production code, you will initialize react-ga once: most likely whenever your page layout is mounted.

In unit tests, you will receive a warning if ReactGA is not initialized:

ReactGA.initialize must be called first or GoogleAnalytics should be loaded
manually

Instead of initializing manually in each test, we can initialize for all Jest tests globally for our frontend by

In jest.config.js in the root level (note that <rootDir> is intentional; it’s a keyword in the Jest config):

module.exports = {
  setupFiles: ['<rootDir>/lib/testutil/setup-jest.js'],
};

Next, we have lib/setup-jest.js (or whatever path you prefer). Per the setupFiles documentation, this should run exactly once before each test file:

/**
 * Run once before every jest test file.
 *
 * Suppresses warnings related to ReactGA.
 */
import ReactGA from 'react-ga';

ReactGA.initialize('dummy', { testMode: true });


Test example

Note that we reset the apiCalls before each test still (perhaps there is a clean way to get a global beforeEach, but I didn’t see one that didn’t require some level of hackery).

/**
 * An example of a Jest test in Typescript.
 */
import { fireEvent, render } from '@testing-library/react';
import ReactGA from 'react-ga';

describe('analytics', () => {
  beforeEach(() => {
    ReactGA.testModeAPI.resetCalls();
  });

  it('correctly sends timing analytics', () => {
    const { getByText } = render(
      <MyView />
    );

    fireEvent.click(getByText(/somebutton/));

    // An example of testing the timing call.
    const timings: number[] = [];
    for (const call of ReactGA.testModeAPI.calls) {
      if (call[0] === 'send' && call[1].hitType === 'timing') {
        timings.push(call[1].timingValue);
      }
    }
    expect(timings).toEqual([2, 3, 5, 9]);
  });
});


Comments