studio-testing

bởi supabase

Chiến lược kiểm thử cho Supabase Studio. Sử dụng khi viết bài kiểm thử, quyết định những gì

npx skills add https://github.com/supabase/supabase --skill studio-testing

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<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-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:

LayerUse for
Static analysisTypes, satisfies, OpenAPI shapes, ESLint, Knip — no runtime test needed
Unit testsNon-trivial pure logic: parsers, SQL/URL builders, scoring, date/state math, permission matrix
Component testsConsequential UI state machines, form submit/rollback, partial failures, flag/permission gates
E2E testsCritical 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 ButtonTooltips) 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:

// 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.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 <option> nodes, so scope queries to the open listbox: within(await screen.findByRole('listbox')).findByRole('option', { name }).
  • Consolidate with test.each: Use test.each for 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.
WhatWhere
MSW template & gotchasreferences/msw-component-tests.md
Pure logic exemplarsapps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.eszip.test.ts, apps/studio/tests/components/Billing/TaxID.utils.test.ts
MSW & partial-failure testsapps/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 queriesapps/studio/tests/routes/new/$slug.test.tsx, apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx
Harness & setupapps/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 skillsstudio-e2e-tests (Playwright E2E), studio-queries (React Query conventions)

Thêm skills từ supabase

ask-the-docs
supabase
Trả lời các câu hỏi về ứng dụng tài liệu Supabase (apps/docs) bằng cách sử dụng kiến trúc được ghi chép, quy trình build và các ghi chú về mẫu đánh giá, đồng thời áp dụng thiết kế tính năng…
clickhouse-logs-queries
supabase
Write, review, and migrate Supabase logs queries against the ClickHouse-backed `logs` table (the `logs.all.otel` analytics endpoint). Use this whenever a task…
copywriting
supabase
Viết hoặc kiểm tra nội dung UI (nút bấm, nhãn, trạng thái trống, thông báo lỗi, chú giải công cụ, văn bản biểu mẫu) ở bất kỳ đâu trong monorepo. Tải nó trước khi phát hành hoặc xem xét bất kỳ…
dev-toolbar-review
supabase
Sử dụng khi xem xét các PR liên quan đến packages/dev-tools/, packages/common/posthog-client.ts,
docs-content
supabase
Viết, chỉnh sửa, sắp xếp và xem lại nội dung Supabase ở bất kỳ đâu trong apps/docs — hướng dẫn, bài giải thích, bài hướng dẫn, mục xử lý sự cố, tài liệu tham khảo, và…
e2e-studio-tests
supabase
Chạy các bài kiểm tra e2e trong ứng dụng Studio. Sử dụng khi được yêu cầu chạy kiểm tra e2e, chạy kiểm tra studio, kiểm tra playwright, hoặc kiểm tra tính năng.
pm-the-docs
supabase
Hỗ trợ ra quyết định Docs-PM cho quy trình biên soạn "Write the docs" — đưa ra các quyết định về đối tượng, giai đoạn và phạm vi xuyên suốt trong các giai đoạn Frame và Shape,…
react-hook-form
supabase
Sử dụng React Hook Form đúng cách ở bất kỳ đâu trong monorepo — luồng dữ liệu, đăng ký, reset, trạng thái dirty, input số và quy tắc input có kiểm soát. Tải cái này…