Files
supabase/apps/studio/tests/helpers.tsx
Alaister YoungandAlaister Young d98f706b7c [FE-5109] (part 1) refactor(studio): migrate core hooks, lib, and prefetchers off next/router (#54053)
Part 1 of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| **1** | **#54053 ← this PR** | **Core navigation helpers, `hooks/**`,
`lib/**`, `data/prefetchers/**`** |
| 2 | #54054 | `components/ui/**` |
| 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` |
| 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| 5 | #54057 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| 6 | #54058 | Remove `next/router` & `next/compat/router` shims,
`_router-events.ts`, Vite aliases, and test mocks |

Introduces the shared TanStack navigation helpers needed across the
stack and migrates `hooks/**`, `lib/**`, and `data/prefetchers/**` off
`next/router`.

**Added:**

- `navigateToUrl` in `apps/studio/lib/navigation.ts` (plus unit tests in
`lib/navigation.test.ts`): shared helper for navigating to internal
string URLs via TanStack's `useNavigate` (splitting pathname, search
params, and hash via `splitInternalUrl`, and handling
external/protocol-relative URLs)
- `useRoutePattern` in `apps/studio/hooks/misc/useRoutePattern.ts` (plus
`useRoutePattern.test.tsx`): returns the active matched TanStack route
template (e.g. `/project/$ref/editor/$id`) as the replacement for Next's
`router.pathname`

**Changed:**

- Migrated `hooks/misc/*` (`useHydratedQuery`,
`useStudioCommandMenuTelemetry`, `useTableEditorFiltersSort`,
`withAuth`) and `hooks/use-check-latest-deploy.tsx` to TanStack's
`useLocation`, `useNavigate`, `useRoutePattern`, and `useParams` from
`common`
- Migrated `lib/profile.tsx` and `lib/telemetry/track.ts` off
`next/router`
- Migrated `data/prefetchers/project.$ref.tsx`,
`project.$ref.editor.tsx`, and `project.$ref.editor.$id.tsx` to
`useRouter().preloadRoute`
- Wrapped `ReactQueryTestConfig` in `apps/studio/tests/helpers.tsx` with
`RouterContextProvider` and updated hook/navigation tests
(`useTableEditorFiltersSort*.test.*`,
`useFilterLifeCycle.navigation.test.tsx`,
`useTableFilter.navigation.test.tsx`, `useInboundBranding.test.ts`,
`state/tabs.test.ts`)

**Simplified:**

- `navigateToUrl` passes `replace` straight through and documents that
`url` must be an app-relative path or an external URL.
`StudioFrameworkProvider`'s `push` now reuses it.
- `useRoutePattern` reads matches and location in a single
`useRouterState` subscription
- `useTrack` and `useStudioCommandMenuTelemetry` take the pathname from
`useFramework()`, the same source as pageviews, so custom events and
pageviews always send the same pattern (e.g. `/project/[ref]/sql/[id]`).
New tests pin the strings sent, and `toRoutePattern` now has its own
unit tests.
- Removed `useCurrentPath` (a one-line wrapper with one consumer):
`OrganizationSettingsLayout` calls `useLocation` directly
- Dropped the no-op `.catch(() => {})` on `preloadRoute` in the
prefetchers (`preloadRoute` never rejects)
- `useTableEditorFiltersSort` builds the next search with a spread
instead of a delete loop
- Added `createTestRouter()` to `tests/lib/custom-render.tsx`, and
`customRender`/`customRenderHook` now return the `router`. The rest of
the stack uses these instead of hand-copied `createRouter` setups.

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] Auth redirect flow (`withAuth`) still preserves `returnTo` query
parameters when redirecting unauthenticated users to `/sign-in`
- [ ] Table Editor sort and filter URL sync
(`useTableEditorFiltersSort`) persists and clears `?sort=` / `?filter=`
across table switches
- [ ] Hovering project and table editor links still triggers route/data
prefetching without console errors
- [ ] Page view and command menu telemetry still records route patterns
and paths accurately

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-27 09:37:49 +00:00

200 lines
5.9 KiB
TypeScript

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RouterContextProvider } from '@tanstack/react-router'
import { fireEvent, getByText, render as originalRender, screen } from '@testing-library/react'
import { platformComponents as components } from 'api-types'
import type React from 'react'
import { useState } from 'react'
import { TooltipProvider } from 'ui'
import { CommandProvider } from 'ui-patterns/CommandMenu'
import type { OrgProject } from '@/data/projects/org-projects-infinite-query'
import { ProjectInfoInfinite } from '@/data/projects/projects-infinite-query'
import { createTestRouter } from '@/tests/lib/custom-render'
import type { Organization } from '@/types'
type OrganizationResponse = components['schemas']['OrganizationResponse_Output']
interface SelectorOptions {
container?: HTMLElement
}
/**
* Returns the toggle button given a text matcher
*
* Defaults to screen if container option is not provided
*/
export const getToggleByText = (
text: string | RegExp,
options: SelectorOptions = {}
): HTMLElement | null => {
const container = options?.container
let textNode
if (container) {
textNode = getByText(container as HTMLElement, text)
} else {
textNode = screen.getByText(text)
}
if (textNode && textNode.parentElement) {
return textNode.parentElement.querySelector('button')
} else {
return textNode
}
}
export const clickDropdown = (elem: HTMLElement) => {
fireEvent.pointerDown(
elem,
new window.PointerEvent('pointerdown', {
ctrlKey: false,
button: 0,
})
)
}
export const createMockOrganization = (details: Partial<Organization> = {}): Organization => {
const base: Organization = {
id: 1,
name: 'Organization 1',
slug: 'abcdefghijklmnopqrst',
plan: { id: 'free', name: 'Free' },
managed_by: 'supabase',
is_owner: true,
billing_email: 'billing@example.com',
billing_partner: null,
integration_source: null,
usage_billing_enabled: false,
stripe_customer_id: 'stripe-1',
subscription_id: 'subscription-1',
organization_requires_mfa: false,
opt_in_tags: [],
restriction_status: null,
requires_indirect_tax_declaration: false,
restriction_data: null,
organization_missing_address: false,
organization_missing_tax_id: false,
}
return Object.assign(base, details)
}
/**
* Returns the raw OpenAPI `OrganizationResponse` shape — without the
* frontend-derived fields (`managed_by`, `partner_id`) that
* `castOrganizationResponseToOrganization` attaches in the query layer.
*
* Use this for MSW mocks at the network boundary (e.g. `/platform/organizations`).
* Use `createMockOrganization` for in-app fixtures that need the cast shape.
*/
export const createMockOrganizationResponse = (
details: Partial<OrganizationResponse> = {}
): OrganizationResponse => {
const base: OrganizationResponse = {
id: 1,
name: 'Organization 1',
slug: 'abcdefghijklmnopqrst',
plan: { id: 'free', name: 'Free' },
is_owner: true,
billing_email: 'billing@example.com',
billing_partner: null,
integration_source: null,
usage_billing_enabled: false,
stripe_customer_id: 'stripe-1',
subscription_id: 'subscription-1',
organization_requires_mfa: false,
opt_in_tags: [],
restriction_status: null,
requires_indirect_tax_declaration: false,
restriction_data: null,
organization_missing_address: false,
organization_missing_tax_id: false,
}
return Object.assign(base, details)
}
export const createMockProject = (details: Partial<ProjectInfoInfinite>): ProjectInfoInfinite => {
const base: ProjectInfoInfinite = {
id: 1,
ref: 'abcdefghijklmnopqrst',
name: 'Project 1',
status: 'ACTIVE_HEALTHY',
organization_id: 1,
cloud_provider: 'AWS',
region: 'us-east-1',
inserted_at: new Date().toISOString(),
subscription_id: 'subscription-1',
is_branch_enabled: false,
is_physical_backups_enabled: false,
organization_slug: 'slug',
preview_branch_refs: [],
}
return Object.assign(base, details)
}
type OrgProjectComputeSize = OrgProject['databases'][number]['infra_compute_size']
/** An org project with a single primary database, as returned by the org projects endpoint. */
export const createMockOrgProject = ({
computeSize = 'micro',
...details
}: Partial<OrgProject> & { computeSize?: OrgProjectComputeSize }): OrgProject => {
const ref = details.ref ?? 'abcdefghijklmnopqrst'
const base: OrgProject = {
ref,
name: 'Project 1',
status: 'ACTIVE_HEALTHY',
cloud_provider: 'AWS',
region: 'us-east-1',
inserted_at: '2026-01-01T00:00:00Z',
is_branch: false,
integration_source: null,
databases: [
{
identifier: ref,
infra_compute_size: computeSize,
region: 'us-east-1',
status: 'ACTIVE_HEALTHY',
type: 'PRIMARY',
cloud_provider: 'AWS',
},
],
}
return Object.assign(base, details)
}
/**
* A custom render function for react testing library
* https://testing-library.com/docs/react-testing-library/setup/#custom-render
*/
const ReactQueryTestConfig: React.FC<React.PropsWithChildren> = ({ children }) => {
const [router] = useState(() => createTestRouter())
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
})
)
return (
<RouterContextProvider router={router}>
<TooltipProvider>
<QueryClientProvider client={queryClient}>
<CommandProvider openKey="">{children}</CommandProvider>
</QueryClientProvider>
</TooltipProvider>
</RouterContextProvider>
)
}
type renderParams = Parameters<typeof originalRender>
export const render = ((ui: renderParams[0], options: renderParams[1]) =>
originalRender(ui, {
wrapper: ReactQueryTestConfig,
...options,
})) as typeof originalRender