mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 08:29:01 +00:00
In Studio's vitest setup, `useParams` from `common` is mocked globally
to return `{ ref: 'default' }`, and `next/router`, `next/compat/router`
and `next/navigation` are mocked with `next-router-mock`. `renderRoute`
mounts a real TanStack memory router, but nothing connected it to those
mocks. So components under a route test never saw the route's path or
search params, and `router.push` from legacy code never moved the
TanStack router. Route tests worked around this by hand-mocking
`useParams` to repeat their URL.
Inside `renderRoute`, these hooks now defer to the app's own
`compat/next` shims, which read the memory router, so they match
runtime: kebab-case keys are camelCased, repeated keys collapse to the
first value, and the hooks follow in-test navigation. All other tests
keep the static mocks.
**Changed:**
- `tests/vitestSetup.ts`: the `common` `useParams`, `next/router`,
`next/compat/router` and `next/navigation` mocks are route-aware.
- `tests/lib/route-render.tsx`: the root route provides a
`RenderedRouteContext` marker. The switch keys off this marker rather
than any TanStack router context, because some component tests mount
their own `RouterContextProvider` or mock `@tanstack/react-router`.
- Route tests that relied on the old behavior:
- The EdgeFunctionOverview self-hosted test, `new/$slug` and
`logs/index.platform` now assert on `router.state.location` instead of
`next-router-mock`.
- The `logs` test's `useSignOut` mock is now stable, like the real hook;
an unstable mock made the redirect effect push in a loop.
- The EdgeFunctionOverview periods test now seeds the function detail
under its real slug instead of `undefined`.
- Removed the hand-written `useParams` mocks from the `authorize`,
Stripe `login`, `sign-in-mfa`, Vercel `new-project` and storage
`vectors` route tests; their URLs carry the params now.
**Added:**
- `tests/lib/route-aware-hooks.ts`: `routeAwareHook` and
`mockNextRouter`.
- `tests/lib/route-render.test.tsx`: renders a route at
`/project/abc/probe?query-tab=logs&id=1&id=2`, asserts what
`useParams()`, `useRouter().query` and `usePathname()` return, then
navigates and asserts again.
Addresses
[FE-5150](https://linear.app/supabase/issue/FE-5150/useparams-in-routes-tests-doesnt-return-any-querystring-params)
## To test
- [ ] `pnpm --filter studio exec vitest --run
tests/lib/route-render.test.tsx` passes.
- [ ] With `tests/vitestSetup.ts`, `tests/lib/route-render.tsx` and
`tests/lib/route-aware-hooks.ts` reverted to `master`, the same test
fails with `expected { ref: 'default' } to deeply equal { ref: 'abc',
queryTab: 'logs', id: '1' }`.
- [ ] Regression checks: `pnpm --filter studio exec vitest --run
tests/routes components/interfaces/Functions
components/interfaces/Database/Replication
components/interfaces/Account/Preferences` passes. These include route
tests and the component tests that mount their own TanStack router or
mock `next/router`.
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
162 lines
5.5 KiB
TypeScript
162 lines
5.5 KiB
TypeScript
import { QueryClient } from '@tanstack/react-query'
|
|
import { fireEvent, screen } from '@testing-library/react'
|
|
import type { components } from 'api-types'
|
|
import { http, HttpResponse } from 'msw'
|
|
import { describe, expect, it } from 'vitest'
|
|
|
|
import { computeQueryOptions } from '@/data/compute/compute-query'
|
|
import { API_URL } from '@/lib/constants'
|
|
import { PRODUCT_NAME } from '@/lib/constants/compute'
|
|
import { Route } from '@/routes/project/$ref/compute/index'
|
|
import { addAPIMock, mswServer, type APIErrorBody } from '@/tests/lib/msw'
|
|
import { renderRoute } from '@/tests/lib/route-render'
|
|
|
|
type ListComputeInstancesResponse = components['schemas']['V2ListComputeInstancesResponse_Output']
|
|
type ComputeInstanceDatum = ListComputeInstancesResponse['data'][number]
|
|
|
|
const PROJECT_REF = 'default'
|
|
|
|
const computeInstanceDatum = (
|
|
id: string,
|
|
attributes: Partial<ComputeInstanceDatum['attributes']> = {}
|
|
): ComputeInstanceDatum => ({
|
|
id,
|
|
type: 'project_compute_instance' as const,
|
|
attributes: {
|
|
build_state: 'active' as const,
|
|
secret_generation: '1',
|
|
spec: { exposure: 'public', instances: 1, runtime: 'node', size: '2gb-1vcpu' },
|
|
...attributes,
|
|
},
|
|
})
|
|
|
|
const mockComputeInstancesList = (instances: ComputeInstanceDatum[]) =>
|
|
addAPIMock({ method: 'get', path: '/v2/projects/:ref/compute', response: { data: instances } })
|
|
|
|
const mockComputeInstancesListFailure = (status: number) =>
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/v2/projects/:ref/compute',
|
|
response: () => HttpResponse.json<APIErrorBody>({ message: 'Denied' }, { status }),
|
|
})
|
|
|
|
// The compute list is platform-only, and `IS_PLATFORM` is false under vitest, so the page's own
|
|
// query never leaves the idle state. Filling the cache imperatively still goes through MSW, and
|
|
// the page reads whatever landed there.
|
|
const renderComputePage = async () => {
|
|
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
|
await queryClient
|
|
.fetchQuery(computeQueryOptions({ projectRef: PROJECT_REF }))
|
|
.catch(() => undefined)
|
|
|
|
return renderRoute(Route, {
|
|
routeId: '/project/$ref/compute/',
|
|
url: `/project/${PROJECT_REF}/compute`,
|
|
queryClient,
|
|
})
|
|
}
|
|
|
|
describe('/project/[ref]/compute', () => {
|
|
it('lists the instances the API returns', async () => {
|
|
mockComputeInstancesList([
|
|
computeInstanceDatum('embed'),
|
|
computeInstanceDatum('resize', {
|
|
build_state: 'building',
|
|
spec: { exposure: 'private', instances: 2, runtime: 'python', size: '4gb-2vcpu' },
|
|
}),
|
|
])
|
|
|
|
await renderComputePage()
|
|
|
|
expect(screen.getByRole('link', { name: 'embed' })).toHaveAttribute(
|
|
'href',
|
|
`/project/${PROJECT_REF}/compute/embed`
|
|
)
|
|
expect(screen.getByRole('link', { name: 'resize' })).toBeVisible()
|
|
expect(screen.getByText('Active')).toBeVisible()
|
|
expect(screen.getByText('Building')).toBeVisible()
|
|
expect(screen.getByText('Python 3.14')).toBeVisible()
|
|
expect(screen.getByText('4 GB · 2 vCPU · 2 inst')).toBeVisible()
|
|
})
|
|
|
|
it('invites you to deploy one when the project has none', async () => {
|
|
mockComputeInstancesList([])
|
|
|
|
await renderComputePage()
|
|
|
|
expect(screen.getByText('Deploy your first Compute instance')).toBeVisible()
|
|
expect(screen.queryByRole('table')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('refreshes the instances list on request', async () => {
|
|
mockComputeInstancesList([computeInstanceDatum('existing')])
|
|
|
|
await renderComputePage()
|
|
|
|
mockComputeInstancesList([computeInstanceDatum('embed')])
|
|
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }))
|
|
|
|
expect(await screen.findByRole('link', { name: 'embed' })).toBeVisible()
|
|
})
|
|
|
|
it('points a project outside the alpha to the waitlist', async () => {
|
|
mswServer.use(
|
|
http.get(`${API_URL}/v2/projects/:ref/compute`, () =>
|
|
HttpResponse.json(
|
|
{
|
|
error: {
|
|
code: 'not_found.compute.not_enabled',
|
|
message: 'Compute is not available for this project',
|
|
},
|
|
},
|
|
{ status: 404 }
|
|
)
|
|
)
|
|
)
|
|
|
|
await renderComputePage()
|
|
|
|
expect(screen.getByText(`You don't have access to ${PRODUCT_NAME} yet`)).toBeVisible()
|
|
expect(screen.getByRole('link', { name: 'Join waitlist' })).toHaveAttribute(
|
|
'href',
|
|
'https://supabase.com/compute'
|
|
)
|
|
expect(screen.queryByText('Failed to retrieve compute instances')).not.toBeInTheDocument()
|
|
expect(screen.queryByRole('table')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('asks for permissions when the project is enrolled but the caller is not allowed', async () => {
|
|
mockComputeInstancesListFailure(403)
|
|
|
|
await renderComputePage()
|
|
|
|
expect(
|
|
screen.getByText("You need additional permissions to view this project's compute instances")
|
|
).toBeVisible()
|
|
expect(screen.queryByRole('table')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('allows retrying an unexpected error', async () => {
|
|
let requestCount = 0
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/v2/projects/:ref/compute',
|
|
response: (): HttpResponse<APIErrorBody> | HttpResponse<ListComputeInstancesResponse> => {
|
|
if (requestCount++ === 0) {
|
|
return HttpResponse.json<APIErrorBody>({ message: 'Unavailable' }, { status: 500 })
|
|
}
|
|
|
|
return HttpResponse.json<ListComputeInstancesResponse>({
|
|
data: [computeInstanceDatum('embed')],
|
|
})
|
|
},
|
|
})
|
|
|
|
await renderComputePage()
|
|
|
|
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }))
|
|
|
|
expect(await screen.findByRole('link', { name: 'embed' })).toBeVisible()
|
|
})
|
|
})
|