React-ga: Test mode - testing a module that uses ReactGA

Created on 11 May 2018  Â·  2Comments  Â·  Source: react-ga/react-ga

We are attempting to test a module that uses ReactGA within function calls as such

// analytics.js
import ReactGA from 'react-ga';

function initialize() {
  ReactGA.initialize('UA-XXXX-1');
}

/**
 * Sends a page view
 * @param {string} [slug]
 * @return void
 */
function firePageView() {
  ReactGA.pageview(window.location.pathname);
}

Then test this with jest as follows:

// analytics.spec.js

describe('firePageView function', () => {
  test('it fires event with correct params', () => {
    Analytics.firePageView();
    ReactGA.testModeAPI.calls.should.eql([
      ['create', 'UA-XXXX-1', 'auto'],
      ['send', 'pageview', '/mypage']
    ]);    
  });
});

Nothing seems to be working and errors are being thrown around what seems to be importing the GA script. I have attempted to use the testMode although the docs are pretty ambiguous on how to use this within such scenario.

Most helpful comment

I’m not sure how it’s ambiguous, you aren’t telling ReactGA that you are running in test mode. ReactGA.initialize('id goes here', { testMode: true }); In your case this is probably going to be testMode: process.env.NODE_ENV === ‘test’ as you are calling the initialisation function all the time.

All 2 comments

I’m not sure how it’s ambiguous, you aren’t telling ReactGA that you are running in test mode. ReactGA.initialize('id goes here', { testMode: true }); In your case this is probably going to be testMode: process.env.NODE_ENV === ‘test’ as you are calling the initialisation function all the time.

Yes that was also my thinking / approach. Although as we import the library within the file analytics.js and then again within analytics.spec.js our functions use the instance of ReactGA that is not in test mode.

How can we possibly have functions that use ReactGA as direct dependancy and initialise ReactGA into test mode within our tests, Like this? ::

// analytics.js
import ReactGA from 'react-ga';

ReactGA.initialize('UA-XXXX-XX', { 
  testMode: process.env.NODE_ENV === ‘test’,
});

function pageView() {
  ReactGA.pageview(window.location.pathname);
}

Was this page helpful?
0 / 5 - 0 ratings

Related issues

TomasVink picture TomasVink  Â·  3Comments

199911 picture 199911  Â·  6Comments

donaldpipowitch picture donaldpipowitch  Â·  4Comments

CJ99 picture CJ99  Â·  3Comments

astroana picture astroana  Â·  5Comments