-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseGoogleAnalytics.test.ts
More file actions
98 lines (81 loc) · 2.56 KB
/
useGoogleAnalytics.test.ts
File metadata and controls
98 lines (81 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
import ReactGA from 'react-ga4'
import {
initializeGoogleAnalytics,
useGoogleAnalyticsPageView,
trackGAEvent
} from './useGoogleAnalytics'
vi.mock('react-ga4', () => ({
default: {
initialize: vi.fn(),
send: vi.fn(),
event: vi.fn()
}
}))
describe('Google Analytics Hooks', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('initializeGoogleAnalytics', () => {
it('should initialize Google Analytics with valid tracking ID', () => {
const trackingId = 'G-XXXXXXXXXX'
initializeGoogleAnalytics(trackingId)
expect(ReactGA.initialize).toHaveBeenCalledWith(trackingId)
})
it('should warn when tracking ID is not provided', () => {
const warnSpy = vi.spyOn(console, 'warn')
initializeGoogleAnalytics('')
expect(warnSpy).toHaveBeenCalledWith(
'Google Analytics: Tracking ID not provided'
)
expect(ReactGA.initialize).not.toHaveBeenCalled()
warnSpy.mockRestore()
})
})
describe('useGoogleAnalyticsPageView', () => {
it('should send page view event on pathname change', () => {
const pathname = '/services'
renderHook(() => useGoogleAnalyticsPageView(pathname))
expect(ReactGA.send).toHaveBeenCalledWith({
hitType: 'pageview',
page: pathname,
title: expect.any(String)
})
})
it('should update page view when pathname changes', () => {
const { rerender } = renderHook(
({ pathname }) => useGoogleAnalyticsPageView(pathname),
{ initialProps: { pathname: '/' } }
)
expect(ReactGA.send).toHaveBeenCalledTimes(1)
rerender({ pathname: '/about' })
expect(ReactGA.send).toHaveBeenCalledTimes(2)
expect(ReactGA.send).toHaveBeenLastCalledWith({
hitType: 'pageview',
page: '/about',
title: expect.any(String)
})
})
})
describe('trackGAEvent', () => {
it('should track event with category and action', () => {
trackGAEvent('engagement', 'click')
expect(ReactGA.event).toHaveBeenCalledWith({
category: 'engagement',
action: 'click',
label: undefined,
value: undefined
})
})
it('should track event with all parameters', () => {
trackGAEvent('engagement', 'button_click', 'cta_button', 1)
expect(ReactGA.event).toHaveBeenCalledWith({
category: 'engagement',
action: 'button_click',
label: 'cta_button',
value: 1
})
})
})
})