mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 08:29:01 +00:00
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>
484 lines
18 KiB
TypeScript
484 lines
18 KiB
TypeScript
import { act, screen, waitFor } from '@testing-library/react'
|
|
import userEvent from '@testing-library/user-event'
|
|
import type { platformComponents as components } from 'api-types'
|
|
import { HttpResponse } from 'msw'
|
|
import type { UrlUpdateEvent } from 'nuqs/adapters/testing'
|
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
|
|
import { Usage } from './Usage'
|
|
import type { Branch } from '@/data/branches/branches-query'
|
|
import { createMockOrganizationResponse, createMockProject } from '@/tests/helpers'
|
|
import { createTestBranch } from '@/tests/lib/branch-test-utils'
|
|
import { customRender } from '@/tests/lib/custom-render'
|
|
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
|
|
import { mockPermissions } from '@/tests/lib/msw-permissions'
|
|
import { ALL_FGA_PERMISSIONS, allPermissionsFor } from '@/tests/lib/permissions-fixtures'
|
|
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
|
|
import { routerMock } from '@/tests/lib/route-mock'
|
|
|
|
vi.mock('common', async (importOriginal) => ({
|
|
...(await importOriginal<typeof import('common')>()),
|
|
useIsLoggedIn: () => true,
|
|
}))
|
|
|
|
vi.mock('@/lib/constants', async (importOriginal) => ({
|
|
...(await importOriginal<typeof import('@/lib/constants')>()),
|
|
IS_PLATFORM: true,
|
|
}))
|
|
|
|
const parent = createMockProject({ ref: 'parent-ref', name: 'Parent project' })
|
|
const branch = createTestBranch({ name: 'Preview branch' })
|
|
const main = createTestBranch({ id: 'main-id', project_ref: parent.ref, is_default: true })
|
|
const parentDetail: components['schemas']['ProjectDetailResponse_Output'] = {
|
|
...parent,
|
|
connectionString: null,
|
|
db_host: 'db.parent-ref.supabase.co',
|
|
high_availability: false,
|
|
integration_source: null,
|
|
inserted_at: '2026-01-01T00:00:00Z',
|
|
is_physical_backups_enabled: false,
|
|
restUrl: 'https://parent-ref.supabase.co',
|
|
status: 'ACTIVE_HEALTHY',
|
|
subscription_id: 'subscription-1',
|
|
updated_at: '2026-01-01T00:00:00Z',
|
|
}
|
|
const branchDetail = {
|
|
...parentDetail,
|
|
ref: branch.project_ref,
|
|
name: branch.name,
|
|
parent_project_ref: parent.ref,
|
|
}
|
|
|
|
function renderUsage(branchRef: string | null = branch.project_ref, projectRef = parent.ref) {
|
|
const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>()
|
|
const searchParams: Record<string, string> = { projectRef }
|
|
if (branchRef !== null) searchParams.branchRef = branchRef
|
|
routerMock.setCurrentUrl({
|
|
pathname: '/org/test-org/usage',
|
|
query: { slug: 'test-org', ...searchParams },
|
|
})
|
|
customRender(<Usage />, {
|
|
initialUrl: '/org/test-org/usage',
|
|
profileContext: createMockProfileContext(),
|
|
nuqs: { searchParams, hasMemory: true, onUrlUpdate },
|
|
})
|
|
return { onUrlUpdate }
|
|
}
|
|
|
|
function captureUsageRequests() {
|
|
const requests: { usage: (string | null)[]; daily: (string | null)[] } = {
|
|
usage: [],
|
|
daily: [],
|
|
}
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations/:slug/usage',
|
|
response: ({ request }) => {
|
|
const ref = new URL(request.url).searchParams.get('project_ref')
|
|
requests.usage.push(ref)
|
|
let usage = 23
|
|
if (ref === branch.project_ref) usage = 7
|
|
if (ref === parent.ref) usage = 13
|
|
return HttpResponse.json<components['schemas']['OrgUsageResponse_Output']>({
|
|
usages: [
|
|
{
|
|
metric: 'EGRESS',
|
|
usage,
|
|
usage_original: usage * 1e9,
|
|
available_in_plan: true,
|
|
capped: true,
|
|
cost: 0,
|
|
pricing_free_units: 5,
|
|
pricing_strategy: 'UNIT',
|
|
project_allocations: [],
|
|
unit_price_desc: 'Egress per GB',
|
|
unlimited: false,
|
|
},
|
|
],
|
|
usage_billing_enabled: false,
|
|
})
|
|
},
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations/:slug/usage/daily',
|
|
response: ({ request }) => {
|
|
requests.daily.push(new URL(request.url).searchParams.get('project_ref'))
|
|
return HttpResponse.json<components['schemas']['OrgDailyUsageResponse_Output']>({
|
|
usages: [],
|
|
})
|
|
},
|
|
})
|
|
return requests
|
|
}
|
|
|
|
function expectUsageRefs(
|
|
requests: ReturnType<typeof captureUsageRequests>,
|
|
refs: (string | null)[]
|
|
) {
|
|
expect(new Set(requests.usage)).toEqual(new Set(refs))
|
|
expect(new Set(requests.daily)).toEqual(new Set(refs))
|
|
}
|
|
|
|
describe('Usage branch URLs', () => {
|
|
beforeEach(() => {
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref',
|
|
response: ({ params }) =>
|
|
HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
|
|
params.ref === branch.project_ref ? branchDetail : parentDetail
|
|
),
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations',
|
|
response: () =>
|
|
HttpResponse.json<components['schemas']['OrganizationResponse_Output'][]>([
|
|
createMockOrganizationResponse({ slug: 'test-org' }),
|
|
]),
|
|
})
|
|
mockPermissions(allPermissionsFor(['test-org']))
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations/:slug/billing/subscription',
|
|
response: () =>
|
|
HttpResponse.json<components['schemas']['GetSubscriptionResponse']>({
|
|
addons: [],
|
|
billing_via_partner: false,
|
|
current_period_start: 1767225600,
|
|
current_period_end: 1769904000,
|
|
next_invoice_at: 1769904000,
|
|
payment_method_type: 'card',
|
|
plan: { id: 'free', name: 'Free' },
|
|
project_addons: [],
|
|
usage_billing_enabled: false,
|
|
}),
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/v1/projects/:ref/branches',
|
|
response: () => HttpResponse.json<Branch[]>([main, branch]),
|
|
})
|
|
})
|
|
|
|
it('shows the permission notice when subscription access is denied', async () => {
|
|
captureUsageRequests()
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations/:slug/projects',
|
|
response: () =>
|
|
HttpResponse.json<components['schemas']['OrganizationProjectsResponse_Output']>({
|
|
projects: [],
|
|
pagination: { count: 0, limit: 96, offset: 0 },
|
|
}),
|
|
})
|
|
mockPermissions({
|
|
organizations: [{ slug: 'test-org', role: 'readonly', permissions: [], projects: [] }],
|
|
})
|
|
const subscriptionRequested = vi.fn()
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations/:slug/billing/subscription',
|
|
response: () => {
|
|
subscriptionRequested()
|
|
return HttpResponse.json<APIErrorBody>({ message: 'Forbidden' }, { status: 403 })
|
|
},
|
|
})
|
|
renderUsage()
|
|
|
|
expect(
|
|
await screen.findByText(/additional permissions to view organization usage/)
|
|
).toBeVisible()
|
|
expect(screen.queryByRole('button', { name: 'Current billing cycle' })).not.toBeInTheDocument()
|
|
expect(subscriptionRequested).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('requests both usage endpoints with the branch project ref from the URL', async () => {
|
|
const requests = captureUsageRequests()
|
|
renderUsage()
|
|
|
|
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
|
|
await waitFor(() => {
|
|
expectUsageRefs(requests, [branch.project_ref])
|
|
})
|
|
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(branch.name)
|
|
expect(screen.queryByText('Branch unavailable')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('resolves a direct branch URL and switches to main and organization totals', async () => {
|
|
const user = userEvent.setup()
|
|
const requests = captureUsageRequests()
|
|
const branchListRefs: string[] = []
|
|
const projectRefs: string[] = []
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref',
|
|
response: ({ params }) => {
|
|
projectRefs.push(String(params.ref))
|
|
return HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
|
|
params.ref === branch.project_ref ? branchDetail : parentDetail
|
|
)
|
|
},
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/v1/projects/:ref/branches',
|
|
response: ({ params }) => {
|
|
branchListRefs.push(String(params.ref))
|
|
return HttpResponse.json<Branch[]>([main, branch])
|
|
},
|
|
})
|
|
const { onUrlUpdate } = renderUsage(null, branch.project_ref)
|
|
|
|
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
|
|
await waitFor(() => {
|
|
expectUsageRefs(requests, [branch.project_ref])
|
|
})
|
|
expect(await screen.findByText('7 GB')).toBeVisible()
|
|
expect(new Set(projectRefs)).toEqual(new Set([branch.project_ref, parent.ref]))
|
|
expect(new Set(branchListRefs)).toEqual(new Set([parent.ref]))
|
|
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(branch.name)
|
|
expect(screen.getByRole('combobox', { name: '' })).toHaveTextContent(parent.name)
|
|
|
|
await user.click(screen.getByLabelText('Filter by branch'))
|
|
await user.click(await screen.findByRole('option', { name: main.name }))
|
|
|
|
expect(await screen.findByText(/Main branch only/)).toBeInTheDocument()
|
|
await waitFor(() => {
|
|
expectUsageRefs(requests, [branch.project_ref, parent.ref])
|
|
})
|
|
expect(await screen.findByText('13 GB')).toBeVisible()
|
|
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(main.name)
|
|
expect(new Set(branchListRefs)).toEqual(new Set([parent.ref]))
|
|
|
|
await user.click(screen.getByLabelText('Filter by branch'))
|
|
await user.click(await screen.findByRole('option', { name: branch.name }))
|
|
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
|
|
|
|
await user.click(screen.getByRole('button', { name: 'View organization total' }))
|
|
|
|
await waitFor(() => {
|
|
expectUsageRefs(requests, [branch.project_ref, parent.ref, null])
|
|
const searchParams = onUrlUpdate.mock.lastCall?.[0].searchParams
|
|
expect(searchParams).toBeDefined()
|
|
expect(searchParams?.has('projectRef')).toBe(false)
|
|
expect(searchParams?.has('branchRef')).toBe(false)
|
|
})
|
|
expect(await screen.findByText('23 / 5 GB')).toBeVisible()
|
|
expect(screen.queryByLabelText('Filter by branch')).not.toBeInTheDocument()
|
|
expect(
|
|
screen.queryByRole('button', { name: 'View organization total' })
|
|
).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('waits for direct branch project details before requesting branches or usage', async () => {
|
|
const requests = captureUsageRequests()
|
|
const response = Promise.withResolvers<void>()
|
|
const projectRequested = vi.fn()
|
|
const branchListRefs: string[] = []
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref',
|
|
response: async ({ params }) => {
|
|
if (params.ref === branch.project_ref) {
|
|
projectRequested()
|
|
await response.promise
|
|
return HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
|
|
branchDetail
|
|
)
|
|
}
|
|
return HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
|
|
parentDetail
|
|
)
|
|
},
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/v1/projects/:ref/branches',
|
|
response: ({ params }) => {
|
|
branchListRefs.push(String(params.ref))
|
|
return HttpResponse.json<Branch[]>([main, branch])
|
|
},
|
|
})
|
|
renderUsage(null, branch.project_ref)
|
|
|
|
try {
|
|
await waitFor(() => expect(projectRequested).toHaveBeenCalled())
|
|
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
|
|
expect(branchListRefs).toEqual([])
|
|
expect(requests).toEqual({ usage: [], daily: [] })
|
|
} finally {
|
|
await act(async () => response.resolve())
|
|
}
|
|
|
|
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
|
|
await waitFor(() => {
|
|
expectUsageRefs(requests, [branch.project_ref])
|
|
})
|
|
expect(new Set(branchListRefs)).toEqual(new Set([parent.ref]))
|
|
})
|
|
|
|
it('blocks a direct branch link when its parent project lookup fails', async () => {
|
|
const requests = captureUsageRequests()
|
|
const branchRequested = vi.fn()
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref',
|
|
response: ({ params }) =>
|
|
params.ref === branch.project_ref
|
|
? HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(branchDetail)
|
|
: HttpResponse.json<APIErrorBody>({ message: 'Parent lookup failed' }, { status: 500 }),
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/v1/projects/:ref/branches',
|
|
response: () => {
|
|
branchRequested()
|
|
return HttpResponse.json<Branch[]>([main, branch])
|
|
},
|
|
})
|
|
renderUsage(null, branch.project_ref)
|
|
|
|
expect(await screen.findByText('Failed to retrieve project')).toBeInTheDocument()
|
|
expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument()
|
|
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
|
|
expect(branchRequested).not.toHaveBeenCalled()
|
|
expect(requests).toEqual({ usage: [], daily: [] })
|
|
})
|
|
|
|
it('does not request parent usage while the branch list is pending', async () => {
|
|
const requests = captureUsageRequests()
|
|
const response = Promise.withResolvers<Branch[]>()
|
|
const branchRequested = vi.fn()
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/v1/projects/:ref/branches',
|
|
response: async () => {
|
|
branchRequested()
|
|
return HttpResponse.json<Branch[]>(await response.promise)
|
|
},
|
|
})
|
|
renderUsage()
|
|
|
|
try {
|
|
await waitFor(() => expect(branchRequested).toHaveBeenCalled())
|
|
expect(await screen.findByText('Free Plan')).toBeInTheDocument()
|
|
expect(screen.getByRole('status', { name: 'Loading branch usage' })).toBeInTheDocument()
|
|
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
|
|
expect(requests).toEqual({ usage: [], daily: [] })
|
|
} finally {
|
|
await act(async () => response.resolve([main, branch]))
|
|
}
|
|
|
|
await waitFor(() => {
|
|
expectUsageRefs(requests, [branch.project_ref])
|
|
})
|
|
})
|
|
|
|
it('shows a branch error without requesting parent usage when the branch list fails', async () => {
|
|
const requests = captureUsageRequests()
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/v1/projects/:ref/branches',
|
|
response: () =>
|
|
HttpResponse.json<APIErrorBody>({ message: 'Branch lookup failed' }, { status: 500 }),
|
|
})
|
|
renderUsage()
|
|
|
|
expect(await screen.findByText('Failed to retrieve branches')).toBeInTheDocument()
|
|
expect(await screen.findByText('Free Plan')).toBeInTheDocument()
|
|
expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument()
|
|
expect(screen.queryByText('Branch unavailable')).not.toBeInTheDocument()
|
|
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
|
|
expect(requests).toEqual({ usage: [], daily: [] })
|
|
})
|
|
|
|
it('blocks branch usage without falling back to the parent when branch access is denied', async () => {
|
|
const requests = captureUsageRequests()
|
|
mockPermissions({
|
|
organizations: [
|
|
{
|
|
slug: 'test-org',
|
|
role: 'owner',
|
|
permissions: ALL_FGA_PERMISSIONS.filter(
|
|
(permission) => !permission.startsWith('branching_')
|
|
),
|
|
projects: [],
|
|
},
|
|
],
|
|
})
|
|
renderUsage()
|
|
|
|
expect(
|
|
await screen.findByText(/additional permissions to view this branch's usage/)
|
|
).toBeVisible()
|
|
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
|
|
expect(requests).toEqual({ usage: [], daily: [] })
|
|
})
|
|
|
|
it('shows Branch unavailable and requests parent usage for a deleted branch ref', async () => {
|
|
const requests = captureUsageRequests()
|
|
renderUsage('deleted-branch-ref')
|
|
|
|
expect(await screen.findByText('Branch unavailable')).toBeInTheDocument()
|
|
expect(screen.getByText(/Main branch only/)).toBeInTheDocument()
|
|
await waitFor(() => {
|
|
expectUsageRefs(requests, [parent.ref])
|
|
})
|
|
})
|
|
|
|
it('keeps filters usable after a project lookup failure and recovers through All projects', async () => {
|
|
const user = userEvent.setup()
|
|
const requests = captureUsageRequests()
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref',
|
|
response: ({ params }) =>
|
|
params.ref === parent.ref
|
|
? HttpResponse.json<APIErrorBody>({ message: 'Project lookup failed' }, { status: 404 })
|
|
: HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(branchDetail),
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations/:slug/projects',
|
|
response: () =>
|
|
HttpResponse.json<components['schemas']['OrganizationProjectsResponse_Output']>({
|
|
projects: [],
|
|
pagination: { count: 0, limit: 96, offset: 0 },
|
|
}),
|
|
})
|
|
const { onUrlUpdate } = renderUsage()
|
|
|
|
expect(await screen.findByText('Failed to retrieve project')).toBeInTheDocument()
|
|
expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument()
|
|
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
|
|
expect(requests).toEqual({ usage: [], daily: [] })
|
|
|
|
await user.click(await screen.findByRole('button', { name: 'Current billing cycle' }))
|
|
expect(
|
|
await screen.findByRole('menuitemradio', { name: 'Current billing cycle' })
|
|
).toBeInTheDocument()
|
|
await user.keyboard('{Escape}')
|
|
|
|
const projectPicker = screen.getByRole('combobox', { name: '' })
|
|
expect(projectPicker).toHaveTextContent(parent.ref)
|
|
await user.click(projectPicker)
|
|
const allProjects = await screen.findByRole('option', { name: 'All projects' })
|
|
expect(screen.getByText('Failed to retrieve project')).toBeInTheDocument()
|
|
expect(requests).toEqual({ usage: [], daily: [] })
|
|
await user.click(allProjects)
|
|
|
|
await waitFor(() => {
|
|
expectUsageRefs(requests, [null])
|
|
const searchParams = onUrlUpdate.mock.lastCall?.[0].searchParams
|
|
expect(searchParams).toBeDefined()
|
|
expect(searchParams?.has('projectRef')).toBe(false)
|
|
expect(searchParams?.has('branchRef')).toBe(false)
|
|
})
|
|
expect(screen.queryByText('Failed to retrieve project')).not.toBeInTheDocument()
|
|
expect(screen.getByText('Usage Summary')).toBeInTheDocument()
|
|
expect(screen.getByRole('combobox', { name: '' })).toHaveTextContent('All projects')
|
|
})
|
|
})
|