单位测试Google标签管理器初始化和事件
我正在尝试在React Project中测试Google标签管理器代码。以下是我要精确测试的内容:
- 如果使用给定的属性初始化Google标签管理器,
- 请检查事件是否良好,并将
使用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))
}
}
我想先了解数据,我该如何渲染组件,按什么顺序渲染,以及如何对此初始化进行测试。
我尝试采用多种方法:
- 尝试直接从窗口上的数据层数组中宣称未定义是不确定的。
- 尝试使用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:
- If Google tag manager is initialized with given properties
- 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:
- Tried directly asserting on Data Layer array from window which turns out is undefined.
- Tried using jest mock to import TagManager library that I am using to load gtag and mock TagManager.initialize and no luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论