简体   繁体   English

如何模拟 google datalayer.push 回调 function?

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

The snippet below displays my React hook file that runs Google Optimize AB test.下面的代码片段显示了我运行 Google Optimize AB 测试的 React hook 文件。

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.我正在尝试测试我的mySideEffectFunction() function 是否会调用以增加测试覆盖率。 In Jest, how do I mock the eventCallback callback function from window.dataLayer.push ?在 Jest 中,如何从window.dataLayer.push eventCallback

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

I managed to mock and call the callback with this.我设法用这个模拟并调用回调。

so in tests we refer to the window as global .所以在测试中我们将window称为global so you could try mocking like this:所以你可以像这样尝试 mocking:

declare global {
    interface Window {
        dataLayer: {
           push: jest.fn().mockImplementation(() => {
                         eventCallback: jest.fn()
                 })
        }
    }
}

I haven't tested this but essentially mocking the dataLayer object and then mocking the functions inside it and mocking the implementations.我没有测试过这个,但本质上是 mocking dataLayer object 然后是 mocking 里面的函数和 mocking 实现。 then you should be able to test if the mocked function was called or not那么您应该能够测试是否调用了模拟的 function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM