javascriptreactjsjestjsgoogle-optimize

How do I mock a google datalayer.push callback function?


The snippet below displays my React hook file that runs Google Optimize AB test.

export default function useGetABExperimentType(experimentId) {
  const [experimentType, setExperimentType] = useState('0');

  useEffect(() => {
    if (window && window.dataLayer) {
      window.dataLayer.push({
        event: 'optimize.activate',
        eventCallback: () => {
          mySideEffectFunction();
        },
      });
    }
  }, []);

  return experimentType;
}

I am trying to test that my mySideEffectFunction() function does call to increase test coverage. In Jest, how do I mock the eventCallback callback function from window.dataLayer.push ?


Solution

  •     window.dataLayer = {
          push: jest.fn().mockImplementation(config => {
            config.eventCallback();
          }),
        };
    

    I managed to mock and call the callback with this.