import { renderHook } from '@testing-library/react' import { StrictMode } from 'react' import { beforeEach, describe, expect, it, vi } from 'vitest' import { usePageviewMetric } from './usePageviewMetric' import { sendFrontendMetric } from '@/lib/frontend-metrics' const mocks = vi.hoisted(() => ({ isEnabled: true, location: { pathname: '/project/abc', search: '', hash: '' }, })) vi.mock('@/lib/constants', () => ({ get IS_STAGING_OR_PREVIEW() { return mocks.isEnabled }, })) vi.mock('@/lib/frontend-metrics', () => ({ sendFrontendMetric: vi.fn() })) vi.mock('@tanstack/react-router', () => ({ useLocation: ({ select }: { select: (location: typeof mocks.location) => unknown }) => select(mocks.location), })) const setLocation = (pathname: string, search = '') => { mocks.location = { pathname, search, hash: '' } } describe('usePageviewMetric', () => { beforeEach(() => { vi.mocked(sendFrontendMetric).mockClear() mocks.isEnabled = true setLocation('/project/abc') }) it('sends once on mount and once per pathname change', () => { const { rerender } = renderHook(() => usePageviewMetric()) expect(sendFrontendMetric).toHaveBeenCalledTimes(1) setLocation('/project/abc/database') rerender() expect(sendFrontendMetric).toHaveBeenCalledTimes(2) }) it('does not send again on a search-only change or a same-pathname re-render', () => { const { rerender } = renderHook(() => usePageviewMetric()) setLocation('/project/abc', '?filter=a') rerender() rerender() expect(sendFrontendMetric).toHaveBeenCalledTimes(1) }) it('sends once on mount under StrictMode', () => { renderHook(() => usePageviewMetric(), { wrapper: StrictMode }) expect(sendFrontendMetric).toHaveBeenCalledTimes(1) }) it('sends nothing when the gate is off', () => { mocks.isEnabled = false const { rerender } = renderHook(() => usePageviewMetric()) setLocation('/project/abc/database') rerender() expect(sendFrontendMetric).not.toHaveBeenCalled() }) })