Files
supabase/.agents/skills/studio-testing/references/msw-component-tests.md

13 KiB

Studio MSW Component Tests

Mount a Studio component, intercept its network calls with MSW, and assert what renders and what gets sent. Load studio-testing first to confirm the change warrants a component test before using this template.

When to use

  • The component (or a rendered descendant) calls a React Query hook or mutation that hits /platform/..., /v1/..., or another endpoint typed in packages/api-types.
  • You would otherwise be tempted to write vi.mock('@/data/some-query', ...). Do not — mock the network instead (see "Why not vi.mock" below).

If the component is purely presentational with no data fetching, render and assert directly without MSW.

The template

import { screen } from '@testing-library/react'
import { platformComponents as components } from 'api-types'
import { mockAnimationsApi } from 'jsdom-testing-mocks'
import { HttpResponse } from 'msw'
import { describe, expect, test } from 'vitest'

import { MyComponent } from './MyComponent'
import { createMockOrganizationResponse } from '@/tests/helpers'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'

type OrganizationResponse = components['schemas']['OrganizationResponse_Output']

mockAnimationsApi()

describe('MyComponent', () => {
  test('renders rows from the API', async () => {
    addAPIMock({
      method: 'get',
      path: '/platform/organizations',
      response: () =>
        HttpResponse.json<OrganizationResponse[]>([
          createMockOrganizationResponse({ name: 'Acme' }),
        ]),
    })

    customRender(<MyComponent />, { profileContext: createMockProfileContext() })

    expect(await screen.findByText('Acme')).toBeInTheDocument()
  })
})

Call mockAnimationsApi() when the component renders Radix UI relying on Web Animations (Sheet, Modal, Popover). Server lifecycle (listen / resetHandlers / close) is managed in apps/studio/tests/vitestSetup.ts — register addAPIMock inside each test or beforeEach (never beforeAll, because handlers reset after every test).

Gotchas that cost debugging time

1. Path params use :slug, not {slug}

addAPIMock remaps OpenAPI {param} segments to MSW's :param syntax:

// ❌ TypeScript error, MSW will not match
path: '/platform/organizations/{slug}/projects'

// ✅ Correct
path: '/platform/organizations/:slug/projects'

2. Match response body semantics (204, 201, and JSON GETs)

  • 204 No Content: Always return a bodyless new HttpResponse(null, { status: 204 }) — never HttpResponse.json({}, { status: 204 }) (204 responses must not carry a body or Content-Type: application/json).
  • 201 Created: Use HttpResponse.json<MyResponse>(body, { status: 201 }) when the OpenAPI schema defines a response body; for empty-body 201 endpoints (content?: never), return a bodyless new HttpResponse(null, { status: 201 }) so the real normalizeEmptyBodyResponse path in apps/studio/data/fetchers.ts is exercised.
  • JSON GET endpoints: Always return a real JSON body via HttpResponse.json<T>(data) — an empty application/json GET throws MalformedResponseError.
// ✅ 204 No Content
response: () => new HttpResponse(null, { status: 204 })

// ✅ 201 with an OpenAPI JSON body (pass explicit generic — see gotcha #8)
response: () => HttpResponse.json<MyResponse>(createdItem, { status: 201 })

3. Submit buttons in Sheets and Modals need fireEvent.click

External form submit buttons (<Button form={FORM_ID} type="submit" />) do not reliably submit under userEvent.click in jsdom. Use fireEvent.click for the submit button (or fireEvent.submit(document.getElementById(FORM_ID)!)), and use user.paste instead of user.type for text inputs:

await user.click(screen.getByPlaceholderText('value'))
await user.paste('hello')
fireEvent.click(await screen.findByRole('button', { name: 'Save' }))

4. Profile-gated queries need profileContext

Hooks gated on a loaded profile (useOrganizationsQuery, data/projects/**, anything calling useProfile) stay idle until profileContext is provided. Reuse createMockProfileContext instead of hand-rolling the object:

import { createMockProfileContext } from '@/tests/lib/profile-helpers'

customRender(<MyComponent />, { profileContext: createMockProfileContext() })

5. Routing and useParams in TanStack Start tests

  • useParams() from 'common' is globally mocked to { ref: 'default' } in apps/studio/tests/vitestSetup.ts, so project-scoped components work out of the box with 'default' in mock URLs.
  • Use renderRoute from @/tests/lib/route-render when testing a TanStack Start file route or when you need a different ref or dynamic route params read via useParams() from 'common' (renderRoute provides RenderedRouteContext so the global useParams mock delegates to the real hook). routeId must match the exact string passed to createFileRoute(...) (including the trailing / for index routes):
    import { renderRoute } from '@/tests/lib/route-render'
    
    await renderRoute(Route, { routeId: '/project/$ref/editor/', url: '/project/my-proj/editor' })
    
  • Pass initialUrl (or router) to customRender when a component reads TanStack Router hooks or useFramework() location/navigation directly (note: common's useParams() still returns { ref: 'default' } under customRender unless the test restores the real useParams implementation):
    const { router } = customRender(<MyComponent />, { initialUrl: '/project/default/issues' })
    

6. Unhandled requests fail loudly

mswServer.listen({ onUnhandledRequest: 'error' }) is enabled globally. If the component or a child fires an unmocked request, mock that endpoint at the network boundary rather than mocking the child component or shared hook. Never add test-only props or injection seams to production components just to avoid rendering a dependency; if a heavy browser-only dependency cannot run in jsdom, extract the independently testable pure logic or cover the full journey in E2E.

7. Read query strings inside the resolver, not in path

addAPIMock strips query params only at the TypeScript type level; MSW v2 ignores query strings in URL path patterns and logs a warning. Omit ?foo=bar from path and read query params from request.url inside the resolver:

addAPIMock({
  method: 'get',
  path: '/platform/projects',
  response: ({ request }) => {
    const limit = new URL(request.url).searchParams.get('limit')
    // ...
  },
})

8. Always pass an explicit generic to HttpResponse.json

MSW's HttpResponse.json uses NoInfer, so pass the OpenAPI response type (or APIErrorBody for errors) explicitly to catch contract drift at compile time:

import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'

response: () => HttpResponse.json<OrganizationResponse[]>([...])
response: () => HttpResponse.json<APIErrorBody>({ message: 'Boom' }, { status: 500 })

Prefer raw OpenAPI response factories like createMockOrganizationResponse over frontend-extended fixtures like createMockOrganization at the network boundary so query mappers still run.

9. Mock FGA permissions and project grant context

Components using useGrant or useAsyncCheckPermissionsV2 fetch /platform/profile/permissions/v2 (no global default). Because FGA permission queries are gated on IS_PLATFORM and authenticated state, name the file *.platform.test.tsx and pass authContext: createMockAuthContext() (@/tests/lib/auth-helpers) and profileContext: createMockProfileContext() to customRender:

import { mockPermissions, mockPermissionsError } from '@/tests/lib/msw-permissions'
import { allPermissionsFor, NO_PERMISSIONS } from '@/tests/lib/permissions-fixtures'
import { mockProjectGrantContext } from '@/tests/lib/project-grant-mocks'

mockPermissions(allPermissionsFor(['my-org']))
mockPermissions(NO_PERMISSIONS)
mockPermissions({
  organizations: [{ slug: 'my-org', role: 'developer', permissions: ['...'], projects: [] }],
})
mockPermissionsError({ status: 500 })

// Shorthand that mocks project detail, organizations, and permissions together:
mockProjectGrantContext({ ref: 'default' })

Reserve testGrant(endpoint, { projectRef }) (@/tests/lib/test-grant) strictly for grant/security contract tests under data/** — not for standard fetcher unit tests. Components should always resolve real grants via useGrant against mocked permissions.

Prefer asserting on UI state

Assert on what the user sees (findByText('Saved'), onClose called, button re-enabled) rather than spying on whether an MSW handler ran. Capture the request body only when the payload itself is the contract and the UI does not observably reflect it (such as a 201 write with no response body):

const requests: Array<{ ref: string | undefined; body: unknown }> = []
addAPIMock({
  method: 'post',
  path: '/v1/projects/:ref/secrets',
  response: async ({ request, params }) => {
    requests.push({ ref: params.ref as string | undefined, body: await request.json() })
    return new HttpResponse(null, { status: 201 })
  },
})

Debugging an MSW test

If a request is not matching, subscribe to MSW events temporarily in the test:

import { mswServer } from '@/tests/lib/msw'

mswServer.events.on('request:unhandled', ({ request }) => {
  console.log('[MSW] UNHANDLED:', request.method, request.url)
})
mswServer.events.on('response:mocked', ({ request, response }) => {
  console.log('[MSW] MATCHED:', request.method, request.url, response.status)
})

Why not vi.mock('@/data/...')

Mocking React Query hooks bypasses the network boundary, hides renamed query keys and broken payloads, skips onMutate/onSuccess/onError and cache invalidation, and drifts independently from packages/api-types. Keep hooks, children, and shared queries real.

Avoid vi.mock for non-network dependencies too — use supported customRender providers/context or an existing injection point rather than adding local module mocks. Use the global harness's supported configuration (vitestSetup.ts, renderRoute) instead of replacing or migrating unrelated harness mocks during a focused test change.

Codebase references

What Where
Query-only example (empty, success, error) apps/studio/components/interfaces/Organization/OrgNotFound.test.tsx
Mutation example (form + payload assertion) apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EditSecretSheet.test.tsx
SQL-via-pg-meta example (branching on query body) apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsx
addAPIMock, customRender, renderRoute apps/studio/tests/lib/msw.ts, apps/studio/tests/lib/custom-render.tsx, apps/studio/tests/lib/route-render.tsx
Profile, permissions, and grant helpers apps/studio/tests/lib/profile-helpers.tsx, apps/studio/tests/lib/msw-permissions.ts, apps/studio/tests/lib/permissions-fixtures.ts, apps/studio/tests/lib/project-grant-mocks.ts, apps/studio/tests/lib/test-grant.ts
Global handlers and lifecycle apps/studio/tests/lib/msw-global-api-mocks.ts, apps/studio/tests/vitestSetup.ts
Related skills studio-testing, studio-queries