studio-testing
Strategi pengujian untuk Supabase Studio. Gunakan saat menulis tes, memutuskan apa
npx skills add https://github.com/supabase/supabase --skill studio-testingStudio Testing Strategy
Write tests only when they guard a plausible runtime regression that static analysis cannot catch. Choose the fastest layer that catches the failure; never add tests merely because a file changed or to chase coverage percentages.
1. "Should I Write a Test?" Gate
Step 1 — Do NOT write a test when the change is solely:
- Static guarantees: TypeScript types,
satisfies Record<K, V>exhaustiveness, OpenAPI request/response shapes, ESLint rules, Knip dead-code checks, or import paths. - Pass-through or declarative code: Pure markup, layout, or styling; static copy or link-href updates; constant maps not verified against an external contract; re-exports; field-assigning constructors; or thin wrappers forwarding props.
- Standard data layer (
apps/studio/data/**): Thin React Query hooks, mutations,openapi-fetchparam forwarding,handleErrorpass-through, orkeys.tsfactories. (Exceptions: non-trivial client transforms/parsers, custom retry/caching state machines, ortestGrantsecurity boundaries.) - Library or language behavior: Zod built-in type/enum/required checks,
TanStack Query staying idle on
{ enabled: false }, Radix opening/closing a dialog, or JavaScript?.,||, andArray.filter. - Trivial one-line predicates: Single-expression boolean checks (e.g.
error?.code === 507) unless part of a multi-branch domain matrix or a regressed bug.
Step 2 — Write the smallest test at the highest-leverage layer for:
| Layer | Use for |
|---|---|
| Static analysis | Types, satisfies, OpenAPI shapes, ESLint, Knip — no runtime test needed |
| Unit tests | Non-trivial pure logic: parsers, SQL/URL builders, scoring, date/state math, permission matrix |
| Component tests | Consequential UI state machines, form submit/rollback, partial failures, flag/permission gates |
| E2E tests | Critical journeys or platform vs self-hosted differences lower layers cannot establish |
Co-locate new tests directly beside the source file (Foo.test.tsx,
Foo.utils.test.ts); older tests still live under apps/studio/tests/. Extract
pure logic to .utils.ts only when it clarifies the component and gives the
logic a real independent contract — never extract a one-liner just to unit-test
it. For a bug fix, reproduce the failure in a test before fixing it.
2. Six Categorical Quality Litmus Tests
Read nearby tests before adding new ones so each test fills a real gap. Run these checks before committing or during code review; failing any check means delete or rewrite the test (when pruning, preserve distinct boundary, permission, security, error, and historical-data cases, and rewrite brittle assertions around observable contracts before deleting a regression's only guard):
- Static-Analysis Kill: If breaking the guarded behavior already fails
pnpm typecheck, ESLint, Knip, or OpenAPI types, delete the test. - Concrete-Regression: State in one sentence a realistic production bug that would ship unnoticed without this test (not "someone edits this string"). If you cannot, delete it.
- Mirror / Tautology: Delete tests that restate implementation literals or
Zod schemas, compute expected values with the helper under test, verify your
mock returned what you configured, or assert on a flag (
{ enabled: false }) the test itself hardcoded. - No-Deformation: Never add an unused optional prop (e.g.
onRedirect), test-only default parameter, or// Exported for testinghelper just to test code. Revert the seam and test the observable boundary, or delete the test. - Behavior-Survives-Refactor: Assert visible text, roles, labels, disabled
state, navigation, or network contracts — never CSS classes (
toHaveClass,querySelector('.flex...')), DOM structure, internal spies, or whole-tree snapshots. NotefocusableWhenDisabledbuttons (including disabledButtonTooltips) setaria-disabled="true"rather thandisabled, so asserttoBeAriaDisabled()ortoHaveAttribute('aria-disabled', 'true'). For SQL generators, normalize withapps/studio/lib/formatSql.tsand assert full formatted SQL instead of fragiletoContainchecks. Remove obsoletevi.mock(...)stubs and stale assertions when refactoring. - Async Honesty: Always
awaitwaitForandexpect(...).resolvesassertions. Never test blocked async submission with bareawait waitFor(() => expect(onSubmit).not.toHaveBeenCalled())— it passes immediately beforeonSubmitruns; assert on a visible validation error or settled UI state instead. Use fake timers, never real sleeps.
3. Concrete Before / After Examples
TypeScript-redundant constant check -> Delete:
// BAD: `EMAIL_TEMPLATE_DOCS_ANCHORS` already uses `satisfies Record<AuthTemplateType, string>`.
it('covers every template type', () => {
expect(Object.keys(EMAIL_TEMPLATE_DOCS_ANCHORS).sort()).toEqual([...AUTH_TEMPLATE_TYPES].sort())
})
// AFTER: Delete the test. Keep constant tests only when checking an external contract
// (e.g. an external package JSON schema).
Thin fetcher or one-line predicate -> Delete (or test the UI outcome):
// BAD: OpenAPI already types query params; `error?.code === 507` is a one-liner.
it('is true for 507', () => expect(isFunctionBodyMaxSizeError({ code: 507 })).toBe(true))
// AFTER: Delete the unit test. If the UI fallback on 507 matters, write one MSW
// component test returning status 507 and asserting the user sees the CLI fallback.
Schema restatement -> Prune built-ins, keep custom rules:
// BAD: Re-testing `z.string()`, `z.enum()`, and required fields across every schema variant.
// AFTER: Delete tests of Zod primitives. Test only custom transforms and cross-field
// invariants (e.g. normalizing `""` to `undefined`, or `start < end` error path attribution).
Test-only prop seam -> Revert seam and delete test:
// BAD: Adding `onRedirect = replaceLocation` with zero production callers just to spy in tests.
// AFTER: Remove the test-only prop and delete the wrapper test. Test pure URL logic
// directly only if it has real parsing or encoding edge cases.
vi.mock('@/data/...') + CSS + broken async -> One behavioral MSW test:
// BAD: vi.mock('@/data/...') + expect(el).toHaveClass('text-destructive-600')
// + await waitFor(() => expect(onSubmit).not.toHaveBeenCalled())
// AFTER: Mock the HTTP endpoint with `addAPIMock`, drive the form, and assert the
// rendered error/recovery state (e.g. `await screen.findByText(/failed/i)`).
4. Component (MSW) & E2E Integration
Mount components with customRender (@/tests/lib/custom-render) and intercept
HTTP calls at the network boundary with addAPIMock (@/tests/lib/msw),
passing an explicit OpenAPI type to HttpResponse.json<T> — never
vi.mock('@/data/...'):
addAPIMock({
method: 'get',
path: '/platform/organizations',
response: () => HttpResponse.json<OrganizationResponse[]>([]),
})
customRender(<MyComponent />)
expect(await screen.findByText('No organizations')).toBeInTheDocument()
Read MSW component tests before writing or
migrating any API-backed component test — it covers the full template, FGA
permissions (mockPermissions, mockProjectGrantContext), profileContext,
TanStack Start route rendering (renderRoute), and jsdom gotchas.
For Playwright journeys, read studio-e2e-tests.
5. Keep Tests Fast
- Use
.test.ts(node) for pure logic;.test.tsx(jsdom) only for DOM:apps/studio/vitest.config.tsruns.test.tsin node and.test.tsxin jsdom (~1s setup per file). Use.test.tsxwhen you need DOM,renderHook, orlocalStorage; use.platform.test.tsxforNEXT_PUBLIC_IS_PLATFORM=true. - Never wait on real time or bump timeouts: Use
vi.useFakeTimers({ shouldAdvanceTime: true })(keepswaitFor, MSW, and router microtasks advancing) inbeforeEachandvi.useRealTimers()inafterEach, then advance withawait act(() => vi.advanceTimersByTimeAsync(INTERVAL_MS))(reusing the production interval/debounce constant). ConfigureuserEvent.setup({ advanceTimers })when combininguserEventwith fake timers. - Paste, don't type: Use
await user.click(input); await user.paste('value')(orfireEvent.change) unless testing per-keystroke behavior. - Scope
*ByRolequeries: RadixSelectrenders hidden<option>nodes, so scope queries to the open listbox:within(await screen.findByRole('listbox')).findByRole('option', { name }). - Consolidate with
test.each: Usetest.eachfor distinct scenarios sharing setup rather than duplicating test blocks (never to multiply equivalent literals).
6. Verify & References
Run relevant existing and new tests with retries disabled
(pnpm --filter studio test --retry=0 <path>, or
pnpm --filter studio exec vitest run --retry=0 <path> to skip coverage — omit
-- so pnpm 12 forwards flags to Vitest), even when no new test was added for a
code change, and run typecheck/formatting separately (Vitest does not prove
TypeScript correctness):
- Environment or dependency failures are blockers, not passes.
- Debugging flakiness or order dependence: Repeat and shuffle with retries
disabled (
--sequence.shuffle --retry=0, recording the seed) and fix shared state, timing, ordering, or cleanup instead of masking failures with retries, longer timeouts, or skips. - Prove new or regression-critical assertions catch failure: Reproduce the bug before fixing when possible, or briefly introduce a realistic scoped fault in the guarded behavior and confirm the assertion fails for that behavior (compile, timeout, and infra failures do not count), restoring exact original bytes and re-running afterward.
| What | Where |
|---|---|
| MSW template & gotchas | references/msw-component-tests.md |
| Pure logic exemplars | apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.eszip.test.ts, apps/studio/tests/components/Billing/TaxID.utils.test.ts |
| MSW & partial-failure tests | apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.platform.test.tsx, apps/studio/components/interfaces/Reports/MetricOptions.test.tsx |
| Fake timers (polling/debounce) | apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsx, apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx |
| Scoped listbox queries | apps/studio/tests/routes/new/$slug.test.tsx, apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx |
| Harness & setup | apps/studio/tests/lib/custom-render.tsx, apps/studio/tests/lib/msw.ts, apps/studio/tests/setup/dom.ts, apps/studio/tests/setup/polyfills.ts, apps/studio/vitest.config.ts |
| Related skills | studio-e2e-tests (Playwright E2E), studio-queries (React Query conventions) |