mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 08:29:01 +00:00
210 lines
12 KiB
Markdown
210 lines
12 KiB
Markdown
---
|
|
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<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:
|
|
|
|
| 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<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):**
|
|
|
|
```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<T>` — never
|
|
`vi.mock('@/data/...')`:
|
|
|
|
```tsx
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations',
|
|
response: () => HttpResponse.json<OrganizationResponse[]>([]),
|
|
})
|
|
customRender(<MyComponent />)
|
|
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 `<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.
|
|
|
|
| What | Where |
|
|
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
| MSW template & gotchas | [references/msw-component-tests.md](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) |
|