Files
supabase/apps/docs/features/IaNav/useIaNavVariant.test.ts
T
Miranda Limonczenkoandcoderabbitai[bot] 33c8ab1dbf feat(docs): keep a forced Option 1 for the browser session (#53381)
Part of DOCS-1474

## Problem

Someone dogfooding the new navigation opens `?docs-ia-mvp-v1=option-1`,
clicks a link, and sees today's navigation again.

The override lives only in the URL. Links do not carry the query string,
so the first click drops it. Everyone who uses the override link is
affected, including people outside the PostHog rollout.

## Solution

- **Save the override:** a forced variant is saved in `sessionStorage`
and read on later pages. Closing the tab clears it.
- **Read it before paint:** the head script reads the saved override, so
a full reload does not flash today's navigation.
- **Keep exposure clean:** a saved override records no PostHog exposure,
the same as a URL override.
- **Switch back:** `?docs-ia-mvp-v1=control` replaces the saved value.

**Priority:** the URL wins over the saved override. The saved override
wins over the PostHog value.

**Not changed:** the `/docs/ia/option-1/…` rewrite that the evals use,
and how PostHog assigns visitors.

**Tests:** `vitest run features/IaNav` passes, 7 files and 32 tests.
Three of the four new tests failed before the change. The fourth, a URL
`control` over a saved `option-1`, passed before and guards the
priority.

**Unverified:** typecheck, ESLint, and the steps below. `tsc` reports no
errors in `IaNav`, but this worktree has no generated GraphQL types.
ESLint did not run.

## Manual testing

1. Open the deploy preview at `/docs?docs-ia-mvp-v1=option-1`. The top
nav shows "Run and manage".
2. Click any guide link. The nav still shows "Run and manage".
3. Reload the page. The nav shows "Run and manage" with no flash of
today's navigation.
4. Open `/docs?docs-ia-mvp-v1=control`, then click any guide link. The
nav shows today's navigation and keeps it.

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-11-13 12:12:07 -08:00

202 lines
7.0 KiB
TypeScript

// @vitest-environment jsdom
import { renderHook } from '@testing-library/react'
import { posthogClient, useFeatureFlags, useSearchParamsShallow } from 'common'
import { LOCAL_STORAGE_KEYS } from 'common/constants/local-storage'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { IA_NAV_FLAG, IA_NAV_OVERRIDE_KEY } from './constants'
import { IaNavRouteProvider } from './IaNavRouteProvider'
import { useIaNavVariant } from './useIaNavVariant'
vi.mock('common', () => ({
useConsentState: vi.fn(() => ({ hasAccepted: true })),
posthogClient: { captureExperimentExposure: vi.fn() },
useFeatureFlags: vi.fn(),
useSearchParamsShallow: vi.fn(),
}))
vi.mock('next/navigation', () => ({
useSelectedLayoutSegments: vi.fn(() => ['ia', 'option-1', 'guides', 'auth']),
}))
const captureExposure = vi.mocked(posthogClient.captureExperimentExposure)
function renderVariant({
flagValue,
override,
isOverrideLoaded = true,
hasLoaded = true,
otherFlags = {},
}: {
flagValue?: string | boolean
override?: string
isOverrideLoaded?: boolean
hasLoaded?: boolean
otherFlags?: Record<string, boolean>
}) {
const posthog = flagValue === undefined ? otherFlags : { ...otherFlags, [IA_NAV_FLAG]: flagValue }
const query = new URLSearchParams(override ? { [IA_NAV_FLAG]: override } : {})
// useSearchParamsShallow starts empty and reads the URL in an effect after mount.
const searchParams = isOverrideLoaded ? query : new URLSearchParams()
window.history.replaceState(null, '', `/?${query}`)
vi.mocked(useFeatureFlags).mockReturnValue({ posthog, hasLoaded } as unknown as ReturnType<
typeof useFeatureFlags
>)
vi.mocked(useSearchParamsShallow).mockReturnValue(
searchParams as unknown as ReturnType<typeof useSearchParamsShallow>
)
return renderHook(() => useIaNavVariant())
}
describe('useIaNavVariant', () => {
beforeEach(() => {
captureExposure.mockClear()
})
afterEach(() => {
localStorage.clear()
sessionStorage.clear()
})
it('keeps a forced option-1 on later pages without the query param, with no exposure', () => {
renderVariant({ flagValue: 'control', override: 'option-1' })
const { result } = renderVariant({ flagValue: 'control' })
expect(result.current).toBe('option-1')
expect(captureExposure).not.toHaveBeenCalled()
})
it('lets a forced control replace a forced option-1 on later pages', () => {
renderVariant({ flagValue: 'option-1', override: 'option-1' })
renderVariant({ flagValue: 'option-1', override: 'control' })
const { result } = renderVariant({ flagValue: 'option-1' })
expect(result.current).toBe('control')
})
it('returns option-1 and records its exposure', () => {
const { result } = renderVariant({ flagValue: 'option-1' })
expect(result.current).toBe('option-1')
expect(captureExposure).toHaveBeenCalledWith(IA_NAV_FLAG, { variant: 'option-1' }, true)
})
it('records control exposure for visitors in the control group', () => {
const { result } = renderVariant({ flagValue: 'control' })
expect(result.current).toBe('control')
expect(captureExposure).toHaveBeenCalledWith(IA_NAV_FLAG, { variant: 'control' }, true)
})
it('falls back to control without exposure for visitors outside the experiment', () => {
const { result } = renderVariant({ flagValue: false })
expect(result.current).toBe('control')
expect(captureExposure).not.toHaveBeenCalled()
})
it('records no exposure when the query param forces option-1', () => {
const { result } = renderVariant({ flagValue: 'control', override: 'option-1' })
expect(result.current).toBe('option-1')
expect(captureExposure).not.toHaveBeenCalled()
})
it('records no exposure before the forcing query param loads', () => {
renderVariant({ flagValue: 'control', override: 'option-1', isOverrideLoaded: false })
expect(captureExposure).not.toHaveBeenCalled()
})
it('ignores an unknown query param value', () => {
const { result } = renderVariant({ flagValue: 'option-1', override: 'nope' })
expect(result.current).toBe('option-1')
expect(captureExposure).toHaveBeenCalledWith(IA_NAV_FLAG, { variant: 'option-1' }, true)
})
it.each([
['option-1', 'control'],
['control', 'option-1'],
])('keeps the session override %s when the URL value is invalid', (sessionVariant, flagValue) => {
sessionStorage.setItem(IA_NAV_OVERRIDE_KEY, sessionVariant)
const { result } = renderVariant({ flagValue, override: 'nope' })
expect(result.current).toBe(sessionVariant)
expect(sessionStorage.getItem(IA_NAV_OVERRIDE_KEY)).toBe(sessionVariant)
expect(captureExposure).not.toHaveBeenCalled()
})
it('uses the cached flag while the flags load, without recording exposure', () => {
localStorage.setItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG, 'option-1')
const { result } = renderVariant({ hasLoaded: false })
expect(result.current).toBe('option-1')
expect(captureExposure).not.toHaveBeenCalled()
})
it('caches the flag once the flags load', () => {
renderVariant({ flagValue: false })
expect(localStorage.getItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG)).toBe('false')
})
it('keeps the cached flag without exposure when the posthog request fails', () => {
localStorage.setItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG, 'option-1')
const { result } = renderVariant({})
expect(result.current).toBe('option-1')
expect(localStorage.getItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG)).toBe('option-1')
expect(captureExposure).not.toHaveBeenCalled()
})
it('drops the cached flag once posthog no longer has it', () => {
localStorage.setItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG, 'option-1')
const { result } = renderVariant({ otherFlags: { 'another-flag': true } })
expect(result.current).toBe('control')
expect(localStorage.getItem(LOCAL_STORAGE_KEYS.IA_NAV_FLAG)).toBe('false')
})
})
describe('useIaNavVariant on the option-1 route', () => {
beforeEach(() => {
captureExposure.mockClear()
})
it('prioritizes the route over conflicting URL and session overrides', () => {
sessionStorage.setItem(IA_NAV_OVERRIDE_KEY, 'control')
renderVariant({ flagValue: 'control', override: 'control' })
const { result } = renderHook(() => useIaNavVariant(), { wrapper: IaNavRouteProvider })
expect(result.current).toBe('option-1')
expect(captureExposure).not.toHaveBeenCalled()
sessionStorage.clear()
})
it('returns option-1 before the URL is read and records no exposure', () => {
vi.mocked(useFeatureFlags).mockReturnValue({
posthog: { [IA_NAV_FLAG]: 'control' },
hasLoaded: true,
} as unknown as ReturnType<typeof useFeatureFlags>)
vi.mocked(useSearchParamsShallow).mockReturnValue(
new URLSearchParams() as unknown as ReturnType<typeof useSearchParamsShallow>
)
window.history.replaceState(null, '', '/')
const { result } = renderHook(() => useIaNavVariant(), { wrapper: IaNavRouteProvider })
expect(result.current).toBe('option-1')
expect(captureExposure).not.toHaveBeenCalled()
})
})