Files
supabase/apps/studio/components/interfaces/APIKeys/CreateAPIKeyDialogs.platform.test.tsx
Alaister YoungandAlaister Young 953e508a3e [FE-5110] refactor(studio): replace next/navigation with TanStack (#54041)
Moves the remaining `next/navigation` imports in Studio onto TanStack
Router hooks (and `useParams` from `common`), finishes migrating the
remaining `next/link` and `next/router` usages in the touched
components, and removes the `compat/next/navigation.ts` shim and its
Vite alias. Shared packages (`packages/**`) no longer import
`next/navigation`, so the alias can be dropped now.

**Removed:**

- `apps/studio/compat/next/navigation.ts` and the `'next/navigation'`
entry in `apps/studio/vite.config.ts`
- Global `next/navigation` mock in `apps/studio/tests/vitestSetup.ts`
and the obsolete `apps/studio/tests/lib/route-mock.test.tsx`

**Changed:**

- Replaced `usePathname` (12 files) and `useSearchParams` (3 files) with
`useLocation({ select })` from `@tanstack/react-router`
- Replaced `useRouter` in Storage bucket tables, SQL Editor commands,
and `SignInMfaForm` with `useNavigate` from `@tanstack/react-router`,
and updated `createNavigationHandler` in `lib/navigation.ts` to accept
either `NextRouter` or TanStack's `useNavigate`
- Replaced remaining `next/link` imports in touched components
(`SignInMfaForm`, `Restriction`, `DownloadLogsButton`,
`DownloadResultsButton`, `AuthEmailsLayout`, `AuthProvidersLayout`,
`JWTKeysLayout`, `StorageBucketsLayout`) with TanStack Router's `Link`
- Replaced `useParams` in `CreatePublishableAPIKeyDialog` with
`useParams` from `common` (matching `CreateSecretAPIKeyDialog`)
- Wrapped `CustomWrapper` (`tests/lib/custom-render.tsx`) in a default
TanStack `RouterContextProvider` (with optional `router` / `initialUrl`
overrides) and updated affected component tests to drop their
`next/navigation` mocks

Addresses
[FE-5110](https://linear.app/supabase/issue/FE-5110/replace-the-nextnavigation-shim-with-tanstack-router-hooks)

## To test

1. Check active tab highlighting and navigation across Auth Emails, Auth
Providers, JWT Keys, Storage Buckets, and Editor layouts
2. Verify clicking, Cmd/Ctrl-clicking, middle-clicking, and pressing
Enter on Storage bucket rows (Files, Analytics, Vector) navigates as
before
3. Run "Query a table..." and open SQL snippets from the Command Menu
and confirm `/project/$ref/sql/$id` opens with multi-line SQL preserved
in `?content=`
4. In the MFA sign-in flow, verify the recovery code link and
`forgot-password` completion preserve query params (`returnTo`,
`context=forgot-password`), and Cancel signs out and replaces history
with `/sign-in`
5. Confirm Table Editor sort/filter URL sync persists filters per table
without leaking across table switches

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-26 17:18:49 +08:00

164 lines
5.6 KiB
TypeScript

import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { CreatePublishableAPIKeyDialog } from './CreatePublishableAPIKeyDialog'
import { CreateSecretAPIKeyDialog } from './CreateSecretAPIKeyDialog'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { customRender as render } from '@/tests/lib/custom-render'
import { mockPermissionsError } from '@/tests/lib/msw-permissions'
import { NO_PERMISSIONS } from '@/tests/lib/permissions-fixtures'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
import { mockProjectGrantContext } from '@/tests/lib/project-grant-mocks'
const { mockSetVisible, mockShortcut, mockUseQueryState } = vi.hoisted(() => ({
mockSetVisible: vi.fn(),
mockShortcut: vi.fn(({ children }: any) => <div data-testid="shortcut">{children}</div>),
mockUseQueryState: vi.fn(),
}))
vi.mock('nuqs', async () => {
const actual = await vi.importActual<typeof import('nuqs')>('nuqs')
return {
...actual,
useQueryState: mockUseQueryState,
}
})
vi.mock('@/components/ui/Shortcut', () => ({
Shortcut: mockShortcut,
}))
vi.mock('common', async () => {
const actual = await vi.importActual<Record<string, unknown>>('common')
return { ...actual, useIsLoggedIn: () => true, useParams: () => ({ ref: 'project-ref' }) }
})
const profileContext = createMockProfileContext()
describe('API key create dialogs', () => {
beforeEach(() => {
mockUseQueryState.mockReturnValue(['', mockSetVisible])
mockProjectGrantContext({ ref: 'project-ref' })
})
it('registers and surfaces the publishable key shortcut on the visible trigger', async () => {
const user = userEvent.setup()
render(<CreatePublishableAPIKeyDialog />, { profileContext })
expect(mockShortcut).toHaveBeenCalledWith(
expect.objectContaining({
id: SHORTCUT_IDS.API_KEYS_NEW_PUBLISHABLE,
onTrigger: expect.any(Function),
}),
undefined
)
const trigger = screen.getByRole('button', { name: 'New publishable key' })
await waitFor(() => expect(trigger).toBeEnabled())
await user.click(trigger)
expect(mockSetVisible).toHaveBeenCalledWith('publishable')
})
it('registers and surfaces the publishable key submit shortcut on the primary action', () => {
mockUseQueryState.mockReturnValue(['publishable', mockSetVisible])
render(<CreatePublishableAPIKeyDialog />, { profileContext })
expect(mockShortcut).toHaveBeenCalledWith(
expect.objectContaining({
id: SHORTCUT_IDS.API_KEYS_CREATE_PUBLISHABLE,
onTrigger: expect.any(Function),
options: { enabled: true },
}),
undefined
)
expect(screen.getByRole('button', { name: 'Create Publishable API key' })).toBeInTheDocument()
})
it('registers and surfaces the secret key shortcut on the visible trigger', async () => {
const user = userEvent.setup()
render(<CreateSecretAPIKeyDialog />, { profileContext })
expect(mockShortcut).toHaveBeenCalledWith(
expect.objectContaining({
id: SHORTCUT_IDS.API_KEYS_NEW_SECRET,
onTrigger: expect.any(Function),
}),
undefined
)
const trigger = screen.getByRole('button', { name: 'New secret key' })
await waitFor(() => expect(trigger).toBeEnabled())
await user.click(trigger)
expect(mockSetVisible).toHaveBeenCalledWith('secret')
})
it('registers and surfaces the secret key submit shortcut on the primary action', () => {
mockUseQueryState.mockReturnValue(['secret', mockSetVisible])
render(<CreateSecretAPIKeyDialog />, { profileContext })
expect(mockShortcut).toHaveBeenCalledWith(
expect.objectContaining({
id: SHORTCUT_IDS.API_KEYS_CREATE_SECRET,
onTrigger: expect.any(Function),
options: { enabled: true },
}),
undefined
)
expect(screen.getByRole('button', { name: 'Create API key' })).toBeInTheDocument()
})
it.each([
{
name: 'denied',
setup: () => mockProjectGrantContext({ ref: 'project-ref', permissions: NO_PERMISSIONS }),
tooltip: 'You need additional permissions to create API keys',
},
{
name: 'a permission-check error',
setup: () => mockPermissionsError(),
tooltip: 'Failed to check permissions to create API keys',
},
])('keeps the create triggers disabled when the grant is $name', async ({ setup, tooltip }) => {
mockProjectGrantContext({ ref: 'project-ref' })
setup()
const user = userEvent.setup()
render(<CreatePublishableAPIKeyDialog />, { profileContext })
render(<CreateSecretAPIKeyDialog />, { profileContext })
const publishable = screen.getByRole('button', { name: 'New publishable key' })
const secret = screen.getByRole('button', { name: 'New secret key' })
// Wait for the grant to settle: the trigger is also disabled while loading
for (const trigger of [publishable, secret]) {
await user.hover(trigger)
expect((await screen.findAllByText(tooltip)).length).toBeGreaterThan(0)
await user.unhover(trigger)
}
expect(publishable).toBeAriaDisabled()
expect(secret).toBeAriaDisabled()
await user.click(publishable)
await user.click(secret)
expect(mockSetVisible).not.toHaveBeenCalled()
})
it('disables the submit button when the grant is denied', async () => {
mockProjectGrantContext({ ref: 'project-ref', permissions: NO_PERMISSIONS })
mockUseQueryState.mockReturnValue(['secret', mockSetVisible])
render(<CreateSecretAPIKeyDialog />, { profileContext })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Create API key' })).toBeDisabled()
)
})
})