// @vitest-environment jsdom import { StrictMode, act } from 'react' import { createRoot } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { usePageviewMetric } from './usePageviewMetric' import { sendFrontendMetric } from '@/lib/frontend-metrics' const mocks = vi.hoisted(() => ({ isEnabled: true, pathname: '/pricing' as string | null, })) vi.mock('@/lib/constants', () => ({ get IS_PREVIEW() { return mocks.isEnabled }, })) vi.mock('@/lib/frontend-metrics', () => ({ sendFrontendMetric: vi.fn() })) vi.mock('next/navigation', () => ({ usePathname: () => mocks.pathname, })) ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true function TestComponent() { usePageviewMetric() return null } describe('usePageviewMetric', () => { let container: HTMLDivElement let root: ReturnType const render = async (strict = false) => { await act(async () => root.render( strict ? ( ) : ( ) ) ) } beforeEach(() => { vi.mocked(sendFrontendMetric).mockClear() mocks.isEnabled = true mocks.pathname = '/pricing' container = document.createElement('div') document.body.appendChild(container) root = createRoot(container) }) afterEach(async () => { await act(async () => root.unmount()) container.remove() }) it('sends once on mount and once per pathname change', async () => { await render() expect(sendFrontendMetric).toHaveBeenCalledTimes(1) expect(sendFrontendMetric).toHaveBeenCalledWith('pageview') mocks.pathname = '/blog' await render() expect(sendFrontendMetric).toHaveBeenCalledTimes(2) }) it('does not send again on a same-pathname re-render', async () => { await render() await render() await render() expect(sendFrontendMetric).toHaveBeenCalledTimes(1) }) it('sends once on mount under StrictMode', async () => { await render(true) expect(sendFrontendMetric).toHaveBeenCalledTimes(1) }) it('skips a null pathname (pages router before the router is ready) and sends once it resolves', async () => { mocks.pathname = null await render() expect(sendFrontendMetric).not.toHaveBeenCalled() mocks.pathname = '/pricing' await render() expect(sendFrontendMetric).toHaveBeenCalledTimes(1) }) it('sends nothing when the gate is off', async () => { mocks.isEnabled = false await render() mocks.pathname = '/blog' await render() expect(sendFrontendMetric).not.toHaveBeenCalled() }) })