React-ga: TypeError: Cannot read property 'parentNode' of undefined

Created on 21 Jan 2019  ·  4Comments  ·  Source: react-ga/react-ga

Tried following the demo file but it was overly complex. Why is it being initialized in the render method?? Shouldn't the init happen at either constructor or CDM level?

Either way, I am also facing an issue with my App.test when I run my build:

> [email protected] test /opt/atlassian/pipelines/agent/build
> react-scripts test
FAIL src/App.test.js
  ● Test suite failed to run
    TypeError: Cannot read property 'parentNode' of undefined
       6 | import ReactGA from 'react-ga';
       7 | 
    >  8 | ReactGA.initialize('UA-132839204-1');
         |         ^
       9 | ReactGA.pageview('/');
      10 | 
      11 | 

Anyone know where to properly initialize or how to avoid this error that's preventing my build?

Most helpful comment

The demo file is kind of a full test-bed kind of example - I put all the weird scenarios that you have to run ga for and can't do tests for in there.

initialize will run the GA code that loads their libraries in the browser - react-ga is convenience functions for interacting with it, you need to use testMode option for running in tests; https://github.com/react-ga/react-ga#test-mode
Many people also do testMode: process.NODE_ENV === 'test' or similar to avoid this.

All 4 comments

The demo file is kind of a full test-bed kind of example - I put all the weird scenarios that you have to run ga for and can't do tests for in there.

initialize will run the GA code that loads their libraries in the browser - react-ga is convenience functions for interacting with it, you need to use testMode option for running in tests; https://github.com/react-ga/react-ga#test-mode
Many people also do testMode: process.NODE_ENV === 'test' or similar to avoid this.

Many people also do testMode: process.NODE_ENV === 'test' or similar to avoid this.

Should be process.env.NODE_ENV, but other than that works a treat 😁

Thank you!

Just adding a +1 for this, adding the testMode property worked for me. For anyone needing it spelled out for them, the OP should replace the initialisation line with:

ReactGA.initialize('UA-132839204-1', { testMode: process.env.NODE_ENV === 'test' });

Was this page helpful?
0 / 5 - 0 ratings

Related issues

199911 picture 199911  ·  6Comments

khmelevskii picture khmelevskii  ·  5Comments

hlodver picture hlodver  ·  4Comments

kenjoe picture kenjoe  ·  4Comments

Dimomir picture Dimomir  ·  3Comments