import { createMemoryHistory, createRootRoute, createRoute, createRouter, Outlet, RouterProvider, type AnyRouter, } from '@tanstack/react-router' import { act, fireEvent, render, screen } from '@testing-library/react' import { useState, type ReactNode } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { HASH_LAYOUT_SETTLE_TIMEOUT_MS, HASH_TARGET_MOUNT_TIMEOUT_MS, HashScrollController, } from './HashScrollController' async function renderWithRouter({ initialUrl = '/other', children, }: { initialUrl?: string children: ReactNode }) { const rootRoute = createRootRoute({ component: () => ( <> ), }) const pageRoute = createRoute({ getParentRoute: () => rootRoute, path: '/page', component: () => <>{children}, }) const otherRoute = createRoute({ getParentRoute: () => rootRoute, path: '/other', component: () =>
Other
, }) const router = createRouter({ routeTree: rootRoute.addChildren([pageRoute, otherRoute]), history: createMemoryHistory({ initialEntries: [initialUrl] }), defaultHashScrollIntoView: false, }) await act(() => router.load()) render() return router } const navigate = ( router: AnyRouter, opts: { to: string; hash: string | true; search?: Record } ) => act(() => router.navigate(opts)) // Flushes pending MutationObserver callbacks. const flushMutations = () => act(async () => {}) /** Renders `target` (or `
`) only after "Finish loading" is clicked, like a query skeleton. */ const LateSection = ({ id, children }: { id: string; children?: ReactNode }) => { const [isLoaded, setIsLoaded] = useState(false) return (
{isLoaded && (children ??
Section
)}
) } describe('HashScrollController', () => { let scrollIntoView: ReturnType beforeEach(() => { vi.useFakeTimers({ shouldAdvanceTime: true }) scrollIntoView = vi.spyOn(HTMLElement.prototype, 'scrollIntoView').mockImplementation(() => {}) }) afterEach(() => { vi.useRealTimers() vi.restoreAllMocks() }) it('smoothly scrolls to the target when navigating to a hash', async () => { const router = await renderWithRouter({ children:
SMS MFA
}) await navigate(router, { to: '/page', hash: 'sms-mfa' }) expect(scrollIntoView).toHaveBeenCalledOnce() expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth', block: 'start' }) expect(scrollIntoView.mock.contexts[0]).toBe(document.getElementById('sms-mfa')) }) it('jumps instead of animating when the user prefers reduced motion', async () => { vi.spyOn(window, 'matchMedia').mockImplementation( (query) => ({ matches: query === '(prefers-reduced-motion: reduce)' }) as MediaQueryList ) const router = await renderWithRouter({ children:
SMS MFA
}) await navigate(router, { to: '/page', hash: 'sms-mfa' }) expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'instant', block: 'start' }) }) it('waits for a target that mounts after the initial render', async () => { await renderWithRouter({ initialUrl: '/page#sms-mfa', children: }) expect(scrollIntoView).not.toHaveBeenCalled() fireEvent.click(screen.getByRole('button', { name: 'Finish loading' })) await flushMutations() expect(scrollIntoView).toHaveBeenCalledOnce() expect(scrollIntoView.mock.contexts[0]).toBe(document.getElementById('sms-mfa')) }) it('gives up once the user scrolls before the target mounts', async () => { await renderWithRouter({ initialUrl: '/page#sms-mfa', children: }) fireEvent.wheel(window) fireEvent.click(screen.getByRole('button', { name: 'Finish loading' })) await flushMutations() expect(scrollIntoView).not.toHaveBeenCalled() }) it('gives up if the target has not mounted by the timeout', async () => { await renderWithRouter({ initialUrl: '/page#sms-mfa', children: }) await act(() => vi.advanceTimersByTimeAsync(HASH_TARGET_MOUNT_TIMEOUT_MS)) fireEvent.click(screen.getByRole('button', { name: 'Finish loading' })) await flushMutations() expect(scrollIntoView).not.toHaveBeenCalled() }) describe('when content above the target shifts', () => { let targetTop: number beforeEach(() => { targetTop = 400 vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function ( this: HTMLElement ) { return { top: this.id === 'compute' ? targetTop : 0 } as DOMRect }) }) // "Finish loading" mounts a banner above the already-mounted target. const renderShiftingPage = () => renderWithRouter({ children: ( <>