Files
supabase/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.platform.test.tsx
T
Alaister YoungandAlaister Young 3b57afc40c fix(studio): wait for project endpoint before showing function url (#53255)
`EdgeFunctionsListItem` built its URL as ``
`${endpoint}/functions/v1/${slug}` `` from `useProjectApiUrl`, whose
`data` is `undefined` while the project settings query is still pending.
On a cold load, each row showed `undefined/functions/v1/<slug>`, and the
copy button copied that string. `EdgeFunctionDetails` and
`TerminalInstructions` interpolated the endpoint the same way.

**Changed:**
-
`apps/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx`:
only builds the URL once `endpoint` is defined. While it's pending, the
row shows a `ShimmeringLoader` in place of the URL and no copy button.
The copy button now has an accessible name ("Copy function URL").
-
`apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx`:
the "Invoke function" snippets wait for both the endpoint and the
function. Until then they show a skeleton, so the cURL tab no longer
renders or copies `undefined/functions/v1/...`. If either query fails,
the card shows an `AlertError` instead.
-
`apps/studio/components/interfaces/Functions/TerminalInstructions.tsx`:
the "Invoke your function" curl command is only added once the endpoint
resolves, with a loader in its place until then.

Also checked: `EdgeFunctionOverviewHeader` already guards on `endpoint
&& slug`, so it's unchanged. `EdgeFunctionTesterSheet` doesn't use
`useProjectApiUrl`: it builds the URL from project settings at submit
time and never renders it, so it's also unchanged. `useProjectApiUrl`
itself is unchanged.

**Added:**
-
`apps/studio/components/interfaces/Functions/EdgeFunctionsListItem.test.tsx`:
renders a row while the settings request is in flight and asserts
there's no `undefined/functions/v1` text, a loader is shown and there's
no copy button. Once settings resolve, it asserts the full URL and that
the copy button copies it. It fails on the old component.
-
`apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.platform.test.tsx`:
a case where project settings fail to load, asserting the invoke card
shows the error and no cURL snippet.

## To test
- [ ] Open a project's Edge Functions page (`/project/<ref>/functions`)
with a hard reload and network throttling (for example "Slow 4G"). The
URL column never shows `undefined`: it shows a loader, then
`https://<ref>.supabase.co/functions/v1/<slug>`.
- [ ] Click a row's copy icon: the clipboard has the full function URL
and the page doesn't navigate.
- [ ] Click a row: it still navigates to that function's page.
- [ ] Hard reload a function's Details page
(`/project/<ref>/functions/<slug>/details`) with throttling. The cURL
snippet under "Invoke function" shows a skeleton, then the real URL.
- [ ] Open `/project/<ref>/functions?create=cli` with throttling. The
"Invoke your function" curl command shows a loader, then the real URL.

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-11 15:57:40 +09:00

197 lines
6.1 KiB
TypeScript

import { QueryClient } from '@tanstack/react-query'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { components } from 'api-types'
import { HttpResponse } from 'msw'
import { describe, expect, it, vi } from 'vitest'
import { EdgeFunctionDetails } from './EdgeFunctionDetails'
import { apiKeysKeys } from '@/data/api-keys/keys'
import { FGA_PERMISSIONS } from '@/hooks/misc/useCheckPermissionsV2'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
import { mockPermissionsError } from '@/tests/lib/msw-permissions'
import { ALL_FGA_PERMISSIONS, type PermissionsV2Response } from '@/tests/lib/permissions-fixtures'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
import { mockProjectGrantContext } from '@/tests/lib/project-grant-mocks'
vi.mock('common', async () => {
const actual = await vi.importActual<Record<string, unknown>>('common')
return {
...actual,
useIsLoggedIn: () => true,
useParams: () => ({ ref: 'default', functionSlug: 'hello' }),
}
})
vi.mock('next/router', () => ({ useRouter: () => ({ push: vi.fn() }) }))
type ApiKeyResponse = components['schemas']['ApiKeyResponse_Output']
type FunctionResponse = components['schemas']['FunctionSlugResponse_Output']
const profileContext = createMockProfileContext()
const withoutKeysRead = (): PermissionsV2Response => ({
organizations: [
{
slug: 'acme',
role: 'developer',
permissions: ALL_FGA_PERMISSIONS.filter(
(permission) => permission !== FGA_PERMISSIONS.PROJECT.API_GATEWAY_KEYS_READ
),
projects: [],
},
],
})
const apiKeys: ApiKeyResponse[] = [
{
type: 'publishable',
name: 'default',
api_key: 'sb_publishable_abc',
id: 'pub-id',
inserted_at: '2024-01-01',
},
]
const mockApiKeys = () => {
const requests = vi.fn()
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/api-keys',
response: () => {
requests()
return HttpResponse.json<ApiKeyResponse[]>(apiKeys)
},
})
return requests
}
const mockFunctionDeps = () => {
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/functions/:function_slug',
response: {
id: 'fn-id',
slug: 'hello',
name: 'hello',
status: 'ACTIVE',
version: 1,
created_at: 1,
updated_at: 1,
verify_jwt: true,
} satisfies FunctionResponse,
})
addAPIMock({
method: 'get',
path: '/platform/projects/:ref/billing/addons',
response: { selected_addons: [], available_addons: [], ref: 'default' },
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/custom-hostname',
response: {
status: '1_not_started',
custom_hostname: '',
data: {
errors: [],
messages: [],
success: true,
result: { hostname: 'api.example.com', id: 'hostname-id' },
},
},
})
addAPIMock({
method: 'get',
path: '/platform/projects/:ref/settings',
response: {
app_config: {
endpoint: 'default.supabase.co',
db_schema: 'public',
storage_endpoint: 'default.supabase.co',
},
cloud_provider: 'AWS',
db_dns_name: 'db.default.supabase.co',
db_host: 'db.default.supabase.co',
db_name: 'postgres',
db_port: 5432,
db_user: 'postgres',
inserted_at: '2026-01-01T00:00:00.000Z',
name: 'Production',
ref: 'default',
region: 'us-east-1',
ssl_enforced: false,
status: 'ACTIVE_HEALTHY',
},
})
}
describe('EdgeFunctionDetails', () => {
it('requests the keys without a note when api-keys are readable', async () => {
mockProjectGrantContext({ ref: 'default' })
const requests = mockApiKeys()
mockFunctionDeps()
customRender(<EdgeFunctionDetails />, { profileContext })
await vi.waitFor(() => expect(requests).toHaveBeenCalled())
expect(screen.queryByText(/need additional permissions/)).not.toBeInTheDocument()
})
it('explains the missing permission and skips the request when denied', async () => {
mockProjectGrantContext({ ref: 'default', permissions: withoutKeysRead() })
const requests = mockApiKeys()
mockFunctionDeps()
customRender(<EdgeFunctionDetails />, { profileContext })
expect(
await screen.findByText(/You need additional permissions to view API keys\./)
).toBeVisible()
expect(requests).not.toHaveBeenCalled()
})
it('does not use cached keys when denied', async () => {
mockProjectGrantContext({ ref: 'default', permissions: withoutKeysRead() })
mockApiKeys()
mockFunctionDeps()
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
queryClient.setQueryData(apiKeysKeys.list('default', false), apiKeys)
customRender(<EdgeFunctionDetails />, { profileContext, queryClient })
expect(
await screen.findByText(/You need additional permissions to view API keys\./)
).toBeVisible()
await userEvent.click(screen.getByRole('button', { name: 'Show anon key' }))
expect(await screen.findByText(/YOUR ANON KEY/)).toBeInTheDocument()
expect(screen.queryByText(/sb_publishable_abc/)).not.toBeInTheDocument()
})
it('shows an error instead of the invoke snippet when the project endpoint fails to load', async () => {
mockProjectGrantContext({ ref: 'default' })
mockApiKeys()
mockFunctionDeps()
addAPIMock({
method: 'get',
path: '/platform/projects/:ref/settings',
response: () =>
HttpResponse.json<APIErrorBody>({ message: 'Settings unavailable' }, { status: 500 }),
})
customRender(<EdgeFunctionDetails />, { profileContext })
expect(await screen.findByText('Failed to retrieve function URL')).toBeVisible()
expect(screen.queryByText(/curl -L -X POST/)).not.toBeInTheDocument()
})
it('shows an error when permissions fail to load', async () => {
mockProjectGrantContext({ ref: 'default' })
mockPermissionsError()
mockFunctionDeps()
customRender(<EdgeFunctionDetails />, { profileContext })
expect(await screen.findByText(/Failed to check API key permissions/)).toBeVisible()
})
})