Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 585
Kevin Avatar asked Sep 13 '26 08:09

Kevin


1 Answers

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

I managed to mock and call the callback with this.

like image 161
Kevin Avatar answered Sep 14 '26 20:09

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!