Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Clarify frontend coding and test authoring guidelines (#84029)

Stas Gavrylovf7f1f254c489
diff --git a/.claude/skills/_shared/development-workflow.md b/.claude/skills/_shared/development-workflow.md
index a4d680a68a3..b08f7385e31 100644
--- a/.claude/skills/_shared/development-workflow.md
+++ b/.claude/skills/_shared/development-workflow.md
@@ -4,6 +4,7 @@
- Add failing tests first, then fix them
- Work autonomously in small, testable increments
- Run targeted tests, and lint continuously during development
-- Prioritize understanding existing patterns before implementing
+- Before relevant edits, read applicable project guidance and the loaded skill's required references in full, including `@` references that your tools don't expand automatically. Searches and excerpts don't replace required reads. Reuse guidance already read for this task unless it changes, and report any required guidance you can't access.
+- Prioritize understanding existing patterns before implementing. Check reused patterns against current guidance; a legacy example does not override a prescribed convention.
- Don't commit changes, leave it for the user to review and make commits
- Minimize comments. Document only non-obvious intent, trade-offs, or constraints that the code itself cannot convey. Do not narrate what the code does — keep code self-descriptive through naming and structure.
diff --git a/.claude/skills/_shared/typescript-commands.md b/.claude/skills/_shared/typescript-commands.md
index 63a19181c19..a3346f69ed9 100644
--- a/.claude/skills/_shared/typescript-commands.md
+++ b/.claude/skills/_shared/typescript-commands.md
@@ -7,13 +7,18 @@
- **Type Check:** `bun run type-check-pure`
- Run TypeScript type checking
+`type-check` and `test-unit` rebuild ClojureScript first, and `lint-format` runs `bun install` first. When you only need the check, use `type-check-pure`, `lint-format-pure`, or `test-unit-keep-cljs`.
+
## Testing
### JavaScript/TypeScript Tests
-- **Test a specific file:** `bun run test-unit-keep-cljs --testPathPatterns=path/to/file.unit.spec.ts`
-- **Test by pattern:** `bun run test-unit-keep-cljs -t "pattern"`
- - Runs tests matching the given pattern
+These reuse existing compiled ClojureScript output:
+
+- **Test specific files:** `bun run test-unit-keep-cljs --runInBand --runTestsByPath path/to/file.unit.spec.tsx`
+ - Use explicit Jest path flags. A bare positional path can be consumed by `--ignoreProjects` in this script and launch an unintended broad run.
+- **Test by name within specific files:** `bun run test-unit-keep-cljs --runInBand --runTestsByPath path/to/file.unit.spec.tsx -t "pattern"`
+ - Runs matching test names only within the specified files.
### ClojureScript Tests
diff --git a/.claude/skills/emotion-migrate/SKILL.md b/.claude/skills/emotion-migrate/SKILL.md
index 67b459ec37b..c0fc8e1f7bb 100644
--- a/.claude/skills/emotion-migrate/SKILL.md
+++ b/.claude/skills/emotion-migrate/SKILL.md
@@ -623,9 +623,9 @@ export const Bar = styled.div<{ width: number }>`
### Pattern 9: Core CSS Utility Classes (Discouraged)
-**Do NOT introduce new `CS` utility class usage.** Core CSS utilities (`CS` from `metabase/css/core/index.css`) are legacy and discouraged for new code. Prefer Mantine style props or CSS modules instead.
+**Don't use `CS` utility classes in new, moved, or otherwise edited code.** Core CSS utilities (`CS` from `metabase/css/core/index.css`) are legacy. Prefer Mantine style props or CSS modules instead.
-If existing code already uses `CS` classes and you're not migrating that specific code, leave them alone. But when migrating Emotion → Mantine, replace with the proper alternative:
+Existing `CS` usage may remain on lines this change neither edits nor moves; editing a neighboring line doesn't require migrating untouched usage. When moving or editing the usage itself, including during an Emotion → Mantine migration, replace it with the proper alternative:
| Instead of `CS.*` | Use |
| ------------------- | ------------------------------------------------------------ |
diff --git a/.claude/skills/typescript-review/SKILL.md b/.claude/skills/typescript-review/SKILL.md
index 975e6695328..2ac8c17913c 100644
--- a/.claude/skills/typescript-review/SKILL.md
+++ b/.claude/skills/typescript-review/SKILL.md
@@ -13,7 +13,9 @@ allowed-tools: Read, Grep, Bash, Glob, Skill
**Primary standard: the [`typescript-write`](../typescript-write/SKILL.md) skill.** Load it first — it defines the authoring rules this review enforces, alongside `frontend/CLAUDE.md` and `docs/developers-guide/frontend.md`.
-Adherence to `typescript-write` is the **highest-priority** review dimension: rank any violation of its provisions above all other findings. Treat its **no-`any` hard rule** (no explicit *or* implicit `any` in new code) as **blocking**. Use TypeScript LSP tools to inspect inferred types when available; otherwise rely on type-checking and linting.
+Adherence to `typescript-write` is the **highest-priority** review dimension: rank any violation of its provisions above all other findings. Treat its **no-`any` hard rule** (no explicit *or* implicit `any` in new, moved, or otherwise edited code) as **blocking**. Use TypeScript LSP tools to inspect inferred types when available; otherwise rely on type-checking and linting.
+
+Read the full diff and new files, including tests and helpers. For tests, check that the setup, actions, and assertions exercise the behavior being claimed. Cite the applicable rule and file/line for violations. Report checks that didn't run or didn't cover the change as unverified, not as passed. Passing automated checks don't establish guideline compliance.
Review in this priority order:
@@ -28,7 +30,7 @@ These rarely surface in team reviews, so this skill should raise them. They are
- **Accessibility.** Interactive elements need keyboard support, focus management, and accessible names. Flag missing `aria-label`/`aria-labelledby`, non-semantic click targets, modals without focus trap, icon-only buttons without labels, and form inputs without a linked label.
- **Performance.** Flag areas that scale poorly and aren't memoized; inline object/array literals passed to memoized children; effects that fire on every batch of a progressive load; and new dependencies added to hot paths.
-- **Security.** Evaluate potential security issues in new code.
+- **Security.** Evaluate potential security issues in new, moved, or otherwise edited code.
- **Bundle size.** Flag new large dependencies, default imports from icon or util libs, and heavy modules imported at route-load time.
- **Analytics.** User-facing flows should emit tracking events. If a PR adds a new flow (button, modal, navigation) without a tracking event, ask whether one is expected.
- **Public API surface** (embedding SDK). Consumers should be able to use public signatures and name types they need to import. Export those types deliberately and document public behaviour, including `@deprecated` for deprecated APIs; a referenced structural type does not automatically need its own named export.
diff --git a/.claude/skills/typescript-write/SKILL.md b/.claude/skills/typescript-write/SKILL.md
index 45ca934c097..0b71fb9c581 100644
--- a/.claude/skills/typescript-write/SKILL.md
+++ b/.claude/skills/typescript-write/SKILL.md
@@ -1,18 +1,21 @@
---
name: typescript-write
-description: Write TypeScript and JavaScript code following Metabase coding standards and best practices. Use when developing or refactoring TypeScript/JavaScript code.
+description: Write or modify TypeScript and JavaScript code, including tests and test helpers, following Metabase coding standards. Use before editing any TS/TSX/JS/JSX file.
---
# TypeScript/JavaScript Development Skill
+Before frontend edits, including test-only changes, read `frontend/CLAUDE.md`, `docs/developers-guide/frontend.md`, and the shared references below. For new or edited tests, follow [Test authoring](#test-authoring).
+
@./../_shared/development-workflow.md
@./../_shared/typescript-commands.md
@./../_shared/react-redux-patterns.md
## No `any` — hard rule
-- **New code must not introduce `any`, explicit or implicit.** No `any` annotations, no `as any` / `as unknown as`, no untyped parameters or returns that infer `any`, no implicitly-`any` destructures or array/object literals.
-- **Untyped third-party / boundary values** must be typed at the boundary (a declared type, `unknown` + type guard, or a small typed wrapper) — never let `any` propagate inward.
+- **New, moved, or otherwise edited code must not contain `any`, explicit or implicit.** No `any` annotations, no `as any` / `as unknown as`, no untyped parameters or returns that infer `any`, no implicitly-`any` destructures or array/object literals.
+- **Stop untyped values at the boundary.** Use canonical types, typed wrappers, or `unknown` with validation or narrowing. Check library defaults and inferred types: a passing type-check does not guarantee that `any` hasn't propagated into your code. For example, capture untyped `JSON.parse` and response `.json()` results as `unknown`; narrow or validate before accessing fields or passing to typed callers.
+- **Type the captured value, not only its eventual result.** A return annotation doesn't change the inferred types of parameters or destructured bindings. Capture untyped data as `unknown`, then narrow or validate before destructuring or accessing fields.
- **Mandatory type verification.** Before finishing a TS/TSX change, run `bun run type-check-pure`. If TypeScript LSP tools are available, also inspect changed symbols with hover and go-to-definition; otherwise skip LSP check.
## Type tightening
@@ -33,7 +36,7 @@ description: Write TypeScript and JavaScript code following Metabase coding stan
## Type modeling
-- **Reuse existing types; don't re-declare them.** Use canonical IDs and domain entity types from `metabase-types/api` (`FieldId`, `TableId`, `ConcreteTableId`, `SchemaName`, …) and key data structures by them (`new Map<ConcreteTableId, …>()`). Don't duplicate generated/API types — compose or derive (`Pick`, `Omit`, indexed access `SomeType["field"]`, `ReturnType`).
+- **Reuse existing types; don't re-declare them.** Use canonical IDs and domain entity types from `metabase-types/api` (`FieldId`, `TableId`, `ConcreteTableId`, `SchemaName`, …) and key data structures by them (`new Map<ConcreteTableId, …>()`). Don't duplicate generated/API types — compose or derive (`Pick`, `Omit`, indexed access `SomeType["field"]`, `ReturnType`). Search for the canonical declaration before introducing a local domain shape. If a type isn't exported directly, derive it from the owning function, endpoint, or hook rather than recreating its shape.
- **Generics must make promises the implementation can keep.** A caller-selected `get<T>(): T` must not disguise an unchecked assertion about external data. Return `unknown` and validate, or accept a validator that establishes `T`. A factory such as `function empty<T>(): T[] { return []; }` is valid; judge the implementation, not how often `T` appears in the signature.
- **Prefer an honest type over false precision.** Use generics when they express a real relationship. If a complex type cannot model the behaviour accurately, choose a simpler type or `unknown` with narrowing instead of asserting an unsupported guarantee.
- **Model the actual data contract; keep types narrow.** Optional `field?: T` for a key that may be absent, `field: T | undefined` only when the key is always present but the value may be undefined, `| null` for explicit API nulls. Prefer domain unions over broad `string` / `number` / loose `Record`.
@@ -92,6 +95,29 @@ description: Write TypeScript and JavaScript code following Metabase coding stan
- **No comments by default**. Well-named identifiers carry the `what`.
- **Comments should be concise**. Add a short, concise comment only when the `why` is non-obvious: a workaround, a hidden invariant, a subtle ordering constraint, a clever reduction. Never document the actual implementation, focus on the intent and the why.
+## Test authoring
+
+Tests should verify expected user-visible behavior or the public contract of a function or component, not its internal implementation. A refactor that preserves that contract should not break the tests.
+
+For new or edited tests, including Jest and Cypress:
+
+1. **Identify the expected contract.** Start from the requirements: what should the user or caller observe? Read the relevant source to understand setup prerequisites and execution paths, not to treat the current implementation as the definition of correct behavior.
+2. **Set up realistic fixtures.** Supply the props, state, mocked data, and providers needed to reach the behavior under test. Data in a mocked endpoint doesn't satisfy a condition on a component prop.
+3. **Plan coverage.** Identify each case's prerequisites, actions, and observable outcomes. For complex scenarios, a short case map can help organize coverage.
+4. **Write the tests** following the rules below.
+5. **Review the finished changes** using [Verify before done](#verify-before-done), including whether each test exercises the behavior it claims.
+6. **Summarize the outcome.** Briefly describe the coverage added and any unresolved issues or checks that didn't run. Follow the user's requested response format.
+
+- **Use the frontend guide's [setup pattern](../../../docs/developers-guide/frontend.md#setup-pattern).** New, moved, or otherwise edited parameterized unit/component setup functions take named options typed as `SetupOpts`, rather than positional selections or booleans.
+- **Keep mocks typed against their real contracts.** Prefer importing the function and using `jest.mocked` for a mocked export. With `jest.requireMock`, supply `typeof import("module-path")` only if the mock preserves that export contract. Give `jest.fn` callbacks a typed implementation or explicit argument/return types matching the real callback; bare `jest.fn()` defaults to `any`.
+- **Type fixtures against the owning contract.** Use canonical response types for mock data and deferred promises. Deriving a type from the fixture itself doesn't establish compatibility with the API. Apply the boundary rule to parsed or intercepted request/response bodies: capture untyped results as `unknown` before using them, including in assertions. Comparing an `unknown` value with an independent expected object doesn't require narrowing it.
+- **Reuse test infrastructure.** Search shared test support before adding providers, server mocks, or async helpers. Use shared [server-mock helpers](../../../docs/developers-guide/frontend.md#request-mocking) for endpoints and, when suitable, `defer<T>()` from `metabase/utils/promise` for controlled async completion. Preserve other callers when extending shared helpers.
+- **Exercise what the test claims.** Repeat actions to test repetition. When checking pending behavior or ordering, control async completion and assert at the relevant intermediate states, not only after everything settles. Check expected effects and the absence of unwanted effects relevant to the contract. If call counts matter, assert them as well as arguments; `toHaveBeenCalledWith` permits extra calls. Before testing a retry, wait for the failure to become observable.
+- **Assert observable outcomes.** Check rendered behavior, return values, or externally observable effects required by the contract. Assert callback arguments, call counts, or ordering only when they are part of that contract, not to mirror internal helper calls or component state. Reuse the applicable testing conventions rather than copying a nearby assertion blindly.
+- **Challenge the assertions.** If the expected behavior were missing or wrong, would this test fail? For multi-step interactions, verify the observable transition between steps—not just the final state.
+- **Preserve the intended coverage when repairing a test.** Correct an ambiguous selector or faulty setup without dropping the behavior the test was meant to exercise. If the assertion itself misstates the expected contract, correct it against the requirements; don't weaken it merely to match the current implementation.
+
## Verify before done
- **Run the project type-check** when finished (see the shared TypeScript commands above).
+- **Review the finished changes.** Use `typescript-review` to check the full diff and new files, including tests and helpers, against the applicable guidelines. Passing tests, lint, and type-checking don't establish guideline compliance.
diff --git a/docs/developers-guide/frontend.md b/docs/developers-guide/frontend.md
index 57d83bb3f5f..4f3d1d29030 100644
--- a/docs/developers-guide/frontend.md
+++ b/docs/developers-guide/frontend.md
@@ -42,7 +42,7 @@ You'll note several styling patterns in the codebase. Currently you should prefe
2. [CSS Modules](https://github.com/css-modules/css-modules) for more complex styling
3. Global utility classes (in `/css/core`) should only be used where Mantine style props cannot be used.
-Other patterns, such as emotion styled components should not be used for new code. Where convenient, please updated deprecated styling patterns to the updated ones.
+Don't use Emotion styled components in new, moved, or otherwise edited code. Untouched legacy usage may remain; editing a neighboring line doesn't require a whole-file migration. When moving or editing the usage itself, use Mantine style props or CSS Modules instead.
Familiarize yourself with Mantine's Layout components. You can often save a lot of CSS with built-in components like [`Center`](https://mantine.dev/core/center/) and [`SimpleGrid`](https://mantine.dev/core/simple-grid/)
@@ -143,7 +143,7 @@ describe("Component", () => {
Key points:
- `setup` function
-- Call helpers from `__support__/server-mocks` to setup endpoints for your data
+- Call helpers from `__support__/server-mocks` to setup endpoints for your data instead of registering raw `fetchMock` routes in component tests. For a new endpoint, add a helper in the appropriate shared server-mock owner and preserve existing callers.
## Localization