单位测试Google标签管理器初始化和事件

发布于 2025-01-27 09:52:48 字数 3133 浏览 4 评论 0原文

我正在尝试在React Project中测试Google标签管理器代码。以下是我要精确测试的内容:

  1. 如果使用给定的属性初始化Google标签管理器,
  2. 请检查事件是否良好,并将

使用gtm初始化的window对象样本组件中的DataLayer推到dataLayer:

 useEffect(() => {
    if (!isLoading) {
      try {
        let dataLayer = {
          userProject: 'project-ui'
        }
        if (typeof data.id !== 'undefined') {
          dataLayer = {
            userId: data.id,
            userProject: 'project-ui'
          }
        }

        const tagManagerArgs = {
          gtmId: process.env.REACT_APP_GTAG_TRACKING,
          dataLayer
        }

        TagManager.initialize(tagManagerArgs)
      } catch (e) {/**/ }
    }
}, [isLoading])

我正在尝试覆盖<<<<<<<<<代码> if(typeof data.id!=='undefined') is !isloading在此处。这是确切的目标。

请注意,数据来自React-Query:

const { isLoading, data } = useQuery([USER_TRACKING_ID], () =>
getLoggedInUserProfile())

我到目前为止为单元测试编写的代码:

  test("Ga loads", async () => {
    window.dataLayer = {
      push: jest.fn().mockImplementation(config => {
        config.eventCallback()
      }),
    }

    render(
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
          <Provider store={store}>
            <MainContainer />
          </Provider>
        </BrowserRouter>
      </QueryClientProvider>
    )
    const { result, waitFor } = renderHook(() => useCustomHook(), {
      wrapper: createWrapper()
    })
  
    await waitFor(() => result.current.isSuccess)

    console.log('test data: ', result.current)
    console.log('data layer data: ', window.dataLayer) // this is throwing undefined
    const eventSpy  = jest.spyOn(TagManager, 'initialize')


    expect(result.current.data).toEqual({
      "employeeId": "797979878",
      "name": "UserFirstName lastName",
      "userEmail": "[email protected]",
      "loginTime": 1652073402000
    })
    expect(window.dataLayer.push).toHaveBeenCalled()
    // expect(eventSpy).toHaveBeenCalled()
  })

我想测试的DataLayer推动之一的示例代码:

    const messageBoardhandler = () => {
    try {
      dataLayer.push({
        event: 'NotificationBoard',
        userId: queryClient.getQueryData('USER_TRACKING_ID').id,
        category: 'MessageBoard',
        action: 'NotificationClicked',
        label: 'NotificationIcon',
        value: ''
      })
    } catch (e) { /* */ }
    dispatch(appCategoryAction.setAppCategoryFlyer(false))
    if (!pinMessageBoard) {
      dispatch(messageBoardActions.setMessageBoardChatFlyer(true))
    }
  }

我想先了解数据,我该如何渲染组件,按什么顺序渲染,以及如何对此初始化进行测试。

我尝试采用多种方法:

  1. 尝试直接从窗口上的数据层数组中宣称未定义是不确定的。
  2. 尝试使用jest模拟导入 tagmanager库我用来加载gtag和gtag和gtag模拟tagmanager。启动,没有运气。

I am trying to Unit test Google tag manager code in React project. Following is what I want to test precisely:

  1. If Google tag manager is initialized with given properties
  2. Check if events are getting fired fine and are being pushed to DataLayer in window object

Sample component with gtm initialization in useEffect:

 useEffect(() => {
    if (!isLoading) {
      try {
        let dataLayer = {
          userProject: 'project-ui'
        }
        if (typeof data.id !== 'undefined') {
          dataLayer = {
            userId: data.id,
            userProject: 'project-ui'
          }
        }

        const tagManagerArgs = {
          gtmId: process.env.REACT_APP_GTAG_TRACKING,
          dataLayer
        }

        TagManager.initialize(tagManagerArgs)
      } catch (e) {/**/ }
    }
}, [isLoading])

I am trying to cover mutation of if (typeof data.id !== 'undefined') as well is !isLoading here. This is the exact goal.

please note data is coming from react-query:

const { isLoading, data } = useQuery([USER_TRACKING_ID], () =>
getLoggedInUserProfile())

Code I have written so far for Unit Testing:

  test("Ga loads", async () => {
    window.dataLayer = {
      push: jest.fn().mockImplementation(config => {
        config.eventCallback()
      }),
    }

    render(
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
          <Provider store={store}>
            <MainContainer />
          </Provider>
        </BrowserRouter>
      </QueryClientProvider>
    )
    const { result, waitFor } = renderHook(() => useCustomHook(), {
      wrapper: createWrapper()
    })
  
    await waitFor(() => result.current.isSuccess)

    console.log('test data: ', result.current)
    console.log('data layer data: ', window.dataLayer) // this is throwing undefined
    const eventSpy  = jest.spyOn(TagManager, 'initialize')


    expect(result.current.data).toEqual({
      "employeeId": "797979878",
      "name": "UserFirstName lastName",
      "userEmail": "[email protected]",
      "loginTime": 1652073402000
    })
    expect(window.dataLayer.push).toHaveBeenCalled()
    // expect(eventSpy).toHaveBeenCalled()
  })

Sample code for one of the dataLayer push I want to test:

    const messageBoardhandler = () => {
    try {
      dataLayer.push({
        event: 'NotificationBoard',
        userId: queryClient.getQueryData('USER_TRACKING_ID').id,
        category: 'MessageBoard',
        action: 'NotificationClicked',
        label: 'NotificationIcon',
        value: ''
      })
    } catch (e) { /* */ }
    dispatch(appCategoryAction.setAppCategoryFlyer(false))
    if (!pinMessageBoard) {
      dispatch(messageBoardActions.setMessageBoardChatFlyer(true))
    }
  }

I want to understand first of as I tried to mock the react-query for data, how shall I render the component and in what order, and how can I get this initialization to be tested.

I tried taking multiple approach:

  1. Tried directly asserting on Data Layer array from window which turns out is undefined.
  2. Tried using jest mock to import TagManager library that I am using to load gtag and mock TagManager.initialize and no luck.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文