--- name: studio-testing description: Testing strategy and quality bar for Supabase Studio (apps/studio). Use when deciding whether a change needs a test, writing unit or component tests, mocking API requests with MSW, reviewing or pruning low-value tests, or debugging test speed and flakiness. --- # Studio 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` 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-fetch` param forwarding, `handleError` pass-through, or `keys.ts` factories. _(Exceptions: non-trivial client transforms/parsers, custom retry/caching state machines, or `testGrant` security 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 `?.`, `||`, and `Array.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): 1. **Static-Analysis Kill:** If breaking the guarded behavior already fails `pnpm typecheck`, ESLint, Knip, or OpenAPI types, delete the test. 2. **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. 3. **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. 4. **No-Deformation:** Never add an unused optional prop (e.g. `onRedirect`), test-only default parameter, or `// Exported for testing` helper just to test code. Revert the seam and test the observable boundary, or delete the test. 5. **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. Note `focusableWhenDisabled` buttons (including disabled `ButtonTooltip`s) set `aria-disabled="true"` rather than `disabled`, so assert `toBeAriaDisabled()` or `toHaveAttribute('aria-disabled', 'true')`. For SQL generators, normalize with `apps/studio/lib/formatSql.ts` and assert full formatted SQL instead of fragile `toContain` checks. Remove obsolete `vi.mock(...)` stubs and stale assertions when refactoring. 6. **Async Honesty:** Always `await` `waitFor` and `expect(...).resolves` assertions. Never test blocked async submission with bare `await waitFor(() => expect(onSubmit).not.toHaveBeenCalled())` — it passes immediately before `onSubmit` runs; 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:** ```ts // BAD: `EMAIL_TEMPLATE_DOCS_ANCHORS` already uses `satisfies Record`. 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):** ```ts // 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:** ```ts // 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:** ```tsx // 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:** ```tsx // 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` — never `vi.mock('@/data/...')`: ```tsx addAPIMock({ method: 'get', path: '/platform/organizations', response: () => HttpResponse.json([]), }) customRender() expect(await screen.findByText('No organizations')).toBeInTheDocument() ``` Read [MSW component tests](references/msw-component-tests.md) 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](../studio-e2e-tests/SKILL.md). ## 5. Keep Tests Fast - **Use `.test.ts` (node) for pure logic; `.test.tsx` (jsdom) only for DOM:** `apps/studio/vitest.config.ts` runs `.test.ts` in node and `.test.tsx` in jsdom (~1s setup per file). Use `.test.tsx` when you need DOM, `renderHook`, or `localStorage`; use `.platform.test.tsx` for `NEXT_PUBLIC_IS_PLATFORM=true`. - **Never wait on real time or bump timeouts:** Use `vi.useFakeTimers({ shouldAdvanceTime: true })` (keeps `waitFor`, MSW, and router microtasks advancing) in `beforeEach` and `vi.useRealTimers()` in `afterEach`, then advance with `await act(() => vi.advanceTimersByTimeAsync(INTERVAL_MS))` (reusing the production interval/debounce constant). Configure `userEvent.setup({ advanceTimers })` when combining `userEvent` with fake timers. - **Paste, don't type:** Use `await user.click(input); await user.paste('value')` (or `fireEvent.change`) unless testing per-keystroke behavior. - **Scope `*ByRole` queries:** Radix `Select` renders hidden `