mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 15:39:13 +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>
90 lines
3.7 KiB
TypeScript
90 lines
3.7 KiB
TypeScript
import { QueryClient } from '@tanstack/react-query'
|
|
import { screen, waitFor } from '@testing-library/react'
|
|
import userEvent from '@testing-library/user-event'
|
|
import { FeatureFlagContext } from 'common'
|
|
import { HttpResponse } from 'msw'
|
|
import { afterEach, expect, it, vi } from 'vitest'
|
|
|
|
import { configKeys } from '@/data/config/keys'
|
|
import { customDomainKeys } from '@/data/custom-domains/keys'
|
|
import type { EdgeFunction } from '@/data/edge-functions/edge-function-query'
|
|
import { edgeFunctionsKeys } from '@/data/edge-functions/keys'
|
|
import { projectKeys } from '@/data/projects/keys'
|
|
import { subscriptionKeys } from '@/data/subscriptions/keys'
|
|
import { Route } from '@/routes/project/$ref/functions/$functionSlug/index'
|
|
import { createMockProject } from '@/tests/helpers'
|
|
import { CustomWrapper } from '@/tests/lib/custom-render'
|
|
import { addAPIMock } from '@/tests/lib/msw'
|
|
import { renderRoute } from '@/tests/lib/route-render'
|
|
|
|
afterEach(() => vi.useRealTimers())
|
|
|
|
it('loads the overview before feature flags and updates metrics with the selected period', async () => {
|
|
vi.useFakeTimers({ toFake: ['Date'] })
|
|
vi.setSystemTime(new Date('2026-03-20T10:37:21Z'))
|
|
const user = userEvent.setup()
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
|
|
})
|
|
queryClient.setQueryData(projectKeys.detail('default'), createMockProject({ ref: 'default' }))
|
|
queryClient.setQueryData(configKeys.settingsV2('default'), {
|
|
app_config: { endpoint: 'default.supabase.co' },
|
|
})
|
|
queryClient.setQueryData(subscriptionKeys.addons('default'), { selected_addons: [] })
|
|
queryClient.setQueryData(customDomainKeys.list('default'), {})
|
|
queryClient.setQueryData<EdgeFunction>(edgeFunctionsKeys.detail('default', 'send-email'), {
|
|
id: 'function-id',
|
|
name: 'Send email',
|
|
slug: 'send-email',
|
|
status: 'ACTIVE',
|
|
version: 2,
|
|
created_at: new Date('2026-03-20T08:00:00Z').valueOf(),
|
|
updated_at: new Date('2026-03-20T09:00:00Z').valueOf(),
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref/analytics/endpoints/functions.combined-stats',
|
|
response: ({ request }) => {
|
|
const interval = new URL(request.url).searchParams.get('interval')
|
|
if (interval === '15min') return HttpResponse.json<{ result: never[] }>({ result: [] })
|
|
const isDaily = interval === '1day'
|
|
return HttpResponse.json<{
|
|
result: Array<{ timestamp: string; avg_execution_time: number }>
|
|
}>({
|
|
result: [
|
|
{ timestamp: '2026-03-20T10:35:00Z', avg_execution_time: isDaily ? 90 : 40 },
|
|
{ timestamp: '2026-03-20T10:36:00Z', avg_execution_time: isDaily ? 90 : 80 },
|
|
],
|
|
})
|
|
},
|
|
})
|
|
addAPIMock({
|
|
method: 'post',
|
|
path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel',
|
|
response: () => HttpResponse.json<{ result: never[] }>({ result: [] }),
|
|
})
|
|
|
|
await renderRoute(Route, {
|
|
routeId: '/project/$ref/functions/$functionSlug/',
|
|
url: '/project/default/functions/send-email',
|
|
renderOptions: {
|
|
wrapper: ({ children }) => (
|
|
<CustomWrapper queryClient={queryClient}>
|
|
<FeatureFlagContext.Provider value={{ configcat: {}, posthog: {}, hasLoaded: false }}>
|
|
{children}
|
|
</FeatureFlagContext.Provider>
|
|
</CustomWrapper>
|
|
),
|
|
},
|
|
})
|
|
|
|
expect(await screen.findByText('60ms')).toBeVisible()
|
|
await user.click(screen.getByRole('button', { name: '15 min' }))
|
|
expect((await screen.findAllByText('No data to show'))[0]).toBeVisible()
|
|
await user.click(screen.getByRole('button', { name: '1 day' }))
|
|
await waitFor(() =>
|
|
expect(screen.getByRole('button', { name: '1 day', pressed: true })).toBeVisible()
|
|
)
|
|
expect(await screen.findByText('90ms')).toBeVisible()
|
|
})
|