import { createRootRoute, createRoute } from '@tanstack/react-router' import { act, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' import { useSnippetIdentity } from './useSnippetIdentity' import { createTestRouter, customRenderHook } from '@/tests/lib/custom-render' import { resetSqlEditorStores, seedSnippet } from '@/tests/lib/sql-editor-test-utils' // `common`'s `useParams` is globally stubbed (see tests/vitestSetup.ts) to a // constant `{ ref: 'default' }` so most tests don't have to think about // routing. This suite is specifically about behavior across route changes, so // it swaps in the real implementation, which the test `FrameworkProvider` in // tests/lib/custom-render.tsx feeds from the TanStack test router. vi.mock('common', async (importOriginal) => { const actual = (await importOriginal()) as object return { ...actual } }) const createSqlRouter = (initialUrl: string) => { const rootRoute = createRootRoute() const sqlRoute = createRoute({ getParentRoute: () => rootRoute, path: '/project/$ref/sql/$id', }) return createTestRouter(initialUrl, rootRoute.addChildren([sqlRoute])) } describe('useSnippetIdentity across route changes', () => { beforeEach(() => { resetSqlEditorStores() }) it('generates a fresh id for each new tab, never reusing the previous one', async () => { seedSnippet({ id: 'existing-tab', sql: 'select existing;' }) const router = createSqlRouter('/project/default/sql/existing-tab') const { result } = customRenderHook(useSnippetIdentity, { router }) await waitFor(() => expect(result.current.id).toEqual('existing-tab')) // Click "+" to open a new tab. await act(async () => { await router.navigate({ href: '/project/default/sql/new?skip=true' }) }) const firstNewTabId = result.current.id expect(firstNewTabId).not.toEqual('existing-tab') // Typing in the new tab creates its snippet and shallow-navigates to it // (mirrors the `navigateToUrl` call inside `useSnippetEditor.handleEditorChange`). seedSnippet({ id: firstNewTabId, sql: 'select typed content;' }) await act(async () => { await router.navigate({ href: `/project/default/sql/${firstNewTabId}` }) }) await waitFor(() => expect(result.current.id).toEqual(firstNewTabId)) // Click "+" again to open a second new tab. await act(async () => { await router.navigate({ href: '/project/default/sql/new?skip=true' }) }) const secondNewTabId = result.current.id expect(secondNewTabId).not.toEqual(firstNewTabId) expect(secondNewTabId).not.toEqual('existing-tab') }) })