@ranimontagna/agent-toolkit 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -8
- package/package.json +1 -1
- package/skills/backend/go/golang-patterns/LICENSE +21 -0
- package/skills/backend/go/golang-patterns/NOTICE.md +10 -0
- package/skills/backend/go/golang-patterns/SKILL.md +674 -0
- package/skills/backend/go/golang-testing/LICENSE +21 -0
- package/skills/backend/go/golang-testing/NOTICE.md +10 -0
- package/skills/backend/go/golang-testing/SKILL.md +329 -0
- package/skills/backend/java/java-coding-standards/LICENSE +21 -0
- package/skills/backend/java/java-coding-standards/NOTICE.md +10 -0
- package/skills/backend/java/java-coding-standards/SKILL.md +383 -0
- package/skills/backend/java/java-junit/LICENSE +21 -0
- package/skills/backend/java/java-junit/NOTICE.md +10 -0
- package/skills/backend/java/java-junit/SKILL.md +64 -0
- package/skills/frontend/react/react-patterns/SKILL.md +4 -4
- package/skills/frontend/react/react-patterns/rules/react/LICENSE +21 -0
- package/skills/frontend/react/react-patterns/rules/react/NOTICE.md +11 -0
- package/skills/frontend/react/react-patterns/rules/react/coding-style.md +109 -0
- package/skills/frontend/react/react-patterns/rules/react/hooks.md +187 -0
- package/skills/frontend/react/react-patterns/rules/react/patterns.md +194 -0
- package/skills/frontend/react/react-patterns/rules/react/security.md +180 -0
- package/skills/frontend/react/react-patterns/rules/react/testing.md +208 -0
- package/skills/frontend/react/react-performance/SKILL.md +2 -2
- package/skills/frontend/react/react-performance/rules/react/LICENSE +21 -0
- package/skills/frontend/react/react-performance/rules/react/NOTICE.md +11 -0
- package/skills/frontend/react/react-performance/rules/react/coding-style.md +109 -0
- package/skills/frontend/react/react-performance/rules/react/hooks.md +187 -0
- package/skills/frontend/react/react-performance/rules/react/patterns.md +194 -0
- package/skills/frontend/react/react-performance/rules/react/security.md +180 -0
- package/skills/frontend/react/react-performance/rules/react/testing.md +208 -0
- package/skills/frontend/react/react-testing/SKILL.md +4 -4
- package/skills/frontend/react/react-testing/rules/react/LICENSE +21 -0
- package/skills/frontend/react/react-testing/rules/react/NOTICE.md +11 -0
- package/skills/frontend/react/react-testing/rules/react/coding-style.md +109 -0
- package/skills/frontend/react/react-testing/rules/react/hooks.md +187 -0
- package/skills/frontend/react/react-testing/rules/react/patterns.md +194 -0
- package/skills/frontend/react/react-testing/rules/react/security.md +180 -0
- package/skills/frontend/react/react-testing/rules/react/testing.md +208 -0
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
---
|
|
2
|
+
paths:
|
|
3
|
+
- "**/*.tsx"
|
|
4
|
+
- "**/*.jsx"
|
|
5
|
+
- "**/components/**/*.ts"
|
|
6
|
+
- "**/components/**/*.js"
|
|
7
|
+
- "**/app/**/*.tsx"
|
|
8
|
+
- "**/pages/**/*.tsx"
|
|
9
|
+
---
|
|
10
|
+
# React Patterns
|
|
11
|
+
|
|
12
|
+
> This file extends the upstream `typescript/patterns.md` and `common/patterns.md` rules with React specific content. For hook-specific rules see [hooks.md](./hooks.md).
|
|
13
|
+
|
|
14
|
+
## Container / Presentational Split
|
|
15
|
+
|
|
16
|
+
Container components own data fetching, state, and side effects. Presentational components receive props and render — no service calls, no hooks beyond local UI state.
|
|
17
|
+
|
|
18
|
+
```tsx
|
|
19
|
+
// Container — owns data
|
|
20
|
+
export function UserPage({ userId }: { userId: string }) {
|
|
21
|
+
const { data: user, isLoading } = useUser(userId);
|
|
22
|
+
if (isLoading) return <Spinner />;
|
|
23
|
+
if (!user) return <NotFound />;
|
|
24
|
+
return <UserCard user={user} onSelect={handleSelect} />;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Presentational — pure
|
|
28
|
+
export function UserCard({ user, onSelect }: { user: User; onSelect: (id: string) => void }) {
|
|
29
|
+
return <button onClick={() => onSelect(user.id)}>{user.name}</button>;
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## State Location Decision Tree
|
|
34
|
+
|
|
35
|
+
1. Used by one component → `useState` inside it
|
|
36
|
+
2. Used by parent + a few children → lift to nearest common ancestor, pass via props
|
|
37
|
+
3. Used across distant branches → React Context **for low-frequency reads only** (theme, auth, locale)
|
|
38
|
+
4. High-frequency updates shared across the tree → external store (Zustand, Jotai, Redux Toolkit)
|
|
39
|
+
5. Server-derived data → server-state library (TanStack Query, SWR, RSC fetch) — not application state
|
|
40
|
+
|
|
41
|
+
Context misused for frequently changing values causes every consumer to re-render on every update.
|
|
42
|
+
|
|
43
|
+
## Server / Client Component Boundary (RSC, Next.js App Router)
|
|
44
|
+
|
|
45
|
+
- Server Components are the default — they run on the server, do not ship to the client, and can `await` directly
|
|
46
|
+
- Client Components opt in with `"use client"` at the top of the file
|
|
47
|
+
- Data flows down: a Server Component can render a Client Component and pass serializable props
|
|
48
|
+
- A Client Component cannot import a Server Component, but it can receive one via `children` or named slots
|
|
49
|
+
|
|
50
|
+
```tsx
|
|
51
|
+
// Server (default)
|
|
52
|
+
export default async function Page() {
|
|
53
|
+
const user = await fetchUser();
|
|
54
|
+
return <UserClient user={user} />;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Client
|
|
58
|
+
"use client";
|
|
59
|
+
export function UserClient({ user }: { user: User }) {
|
|
60
|
+
const [tab, setTab] = useState("profile");
|
|
61
|
+
return <Tabs value={tab} onChange={setTab}>{user.name}</Tabs>;
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- Never import `"server-only"` packages (DB clients, secrets) from a Client Component file — wrap them in a Server Component or Server Action
|
|
66
|
+
- Mark sensitive modules with `import "server-only"` so the bundler errors if a client file imports them
|
|
67
|
+
|
|
68
|
+
## Suspense + Error Boundaries
|
|
69
|
+
|
|
70
|
+
Every Suspense boundary needs an Error Boundary above it. The pair handles both states.
|
|
71
|
+
|
|
72
|
+
```tsx
|
|
73
|
+
<ErrorBoundary fallback={<ErrorView />}>
|
|
74
|
+
<Suspense fallback={<Skeleton />}>
|
|
75
|
+
<UserDetails id={id} />
|
|
76
|
+
</Suspense>
|
|
77
|
+
</ErrorBoundary>
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
- Place Suspense boundaries close to where data is needed, not at the route root
|
|
81
|
+
- Multiple narrower boundaries reveal loaded content progressively
|
|
82
|
+
- Error Boundary must be a Class Component (React 19 has no functional equivalent yet) OR use a library wrapper such as `react-error-boundary`
|
|
83
|
+
|
|
84
|
+
## Forms
|
|
85
|
+
|
|
86
|
+
### Uncontrolled (React 19 + form actions)
|
|
87
|
+
|
|
88
|
+
Prefer uncontrolled inputs with form actions when the form has a clear submit step. The browser owns the value; React reads it via `FormData` on submit.
|
|
89
|
+
|
|
90
|
+
```tsx
|
|
91
|
+
async function action(formData: FormData) {
|
|
92
|
+
"use server";
|
|
93
|
+
await saveUser({ name: String(formData.get("name")) });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function UserForm() {
|
|
97
|
+
return (
|
|
98
|
+
<form action={action}>
|
|
99
|
+
<input name="name" required />
|
|
100
|
+
<button type="submit">Save</button>
|
|
101
|
+
</form>
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Controlled
|
|
107
|
+
|
|
108
|
+
Use controlled inputs when the value drives other UI, requires real-time validation, or formatting.
|
|
109
|
+
|
|
110
|
+
```tsx
|
|
111
|
+
const [email, setEmail] = useState("");
|
|
112
|
+
return <input value={email} onChange={(e) => setEmail(e.target.value)} />;
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Form Libraries
|
|
116
|
+
|
|
117
|
+
For complex forms (multi-step, dynamic field arrays, cross-field validation), use a library:
|
|
118
|
+
|
|
119
|
+
- React Hook Form — minimal re-renders, uncontrolled-first
|
|
120
|
+
- TanStack Form — typed, framework-agnostic
|
|
121
|
+
- Final Form — when subscription-based re-renders matter
|
|
122
|
+
|
|
123
|
+
## Data Fetching
|
|
124
|
+
|
|
125
|
+
| Strategy | When |
|
|
126
|
+
|---|---|
|
|
127
|
+
| RSC fetch (`await` in Server Component) | Per-request data in Next.js App Router, no client-side cache needed |
|
|
128
|
+
| TanStack Query | Client-side cache, mutations, optimistic updates, polling |
|
|
129
|
+
| SWR | Lightweight cache + revalidation, simpler than TanStack Query |
|
|
130
|
+
| `fetch` in `useEffect` | Avoid — race conditions, no cache, no retry. Only acceptable for one-off fire-and-forget |
|
|
131
|
+
|
|
132
|
+
Never fetch in a `useEffect` when a real cache library is available — they handle deduping, cache invalidation, error retry, and Suspense integration.
|
|
133
|
+
|
|
134
|
+
## Lists and Keys
|
|
135
|
+
|
|
136
|
+
- `key` must be stable across renders — never `index` for any list that can reorder, insert, or delete
|
|
137
|
+
- `key` must be unique among siblings, not globally
|
|
138
|
+
- A reordered list with index keys causes state in child components to attach to the wrong row
|
|
139
|
+
|
|
140
|
+
## Composition over Inheritance
|
|
141
|
+
|
|
142
|
+
- Pass `children` for slot-style composition
|
|
143
|
+
- Pass render-prop functions for parameterized rendering
|
|
144
|
+
- Pass component types for plug-in points: `renderItem={UserRow}`
|
|
145
|
+
- Never extend a component class to specialize behavior
|
|
146
|
+
|
|
147
|
+
## Compound Components
|
|
148
|
+
|
|
149
|
+
For related controls (Tabs, Accordion, Menu), use compound components sharing state via Context:
|
|
150
|
+
|
|
151
|
+
```tsx
|
|
152
|
+
<Tabs defaultValue="profile">
|
|
153
|
+
<Tabs.List>
|
|
154
|
+
<Tabs.Trigger value="profile">Profile</Tabs.Trigger>
|
|
155
|
+
<Tabs.Trigger value="settings">Settings</Tabs.Trigger>
|
|
156
|
+
</Tabs.List>
|
|
157
|
+
<Tabs.Panel value="profile"><ProfileForm /></Tabs.Panel>
|
|
158
|
+
<Tabs.Panel value="settings"><SettingsForm /></Tabs.Panel>
|
|
159
|
+
</Tabs>
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Portals
|
|
163
|
+
|
|
164
|
+
Use `createPortal` for modals, tooltips, toast containers — anything that must escape the parent's `overflow: hidden` or `z-index` stacking context. Render to a stable DOM node mounted in `index.html`.
|
|
165
|
+
|
|
166
|
+
## Refs and Forwarding (React 19+)
|
|
167
|
+
|
|
168
|
+
React 19 lets function components accept `ref` as a regular prop — `forwardRef` is no longer required.
|
|
169
|
+
|
|
170
|
+
```tsx
|
|
171
|
+
export function Input({ ref, ...rest }: { ref?: React.Ref<HTMLInputElement> } & InputProps) {
|
|
172
|
+
return <input ref={ref} {...rest} />;
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Older codebases on React 18 still need `forwardRef`.
|
|
177
|
+
|
|
178
|
+
## Out of Scope (Pointer Sections)
|
|
179
|
+
|
|
180
|
+
### Next.js (App Router)
|
|
181
|
+
|
|
182
|
+
- Server Actions, Route Handlers, Middleware, Parallel/Intercepted Routes, streaming Metadata
|
|
183
|
+
- Treated as a separate framework concern — when adding deep Next-specific patterns, propose a dedicated `rules/nextjs/` track
|
|
184
|
+
- For now follow Next.js official docs for App Router specifics
|
|
185
|
+
|
|
186
|
+
### React Native
|
|
187
|
+
|
|
188
|
+
- Platform-specific imports (`Platform.OS`, `.ios.tsx` / `.android.tsx`), `StyleSheet`, navigation libraries (React Navigation, Expo Router)
|
|
189
|
+
- Treated as a separate track — `rules/react-native/` is not yet present
|
|
190
|
+
- React core hooks/patterns from this file still apply
|
|
191
|
+
|
|
192
|
+
## Skill Reference
|
|
193
|
+
|
|
194
|
+
For React-specific deep dives see `skills/react-patterns/SKILL.md`. For cross-framework frontend concerns see `skills/frontend-patterns/SKILL.md`. For accessibility see `skills/accessibility/SKILL.md`.
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
---
|
|
2
|
+
paths:
|
|
3
|
+
- "**/*.tsx"
|
|
4
|
+
- "**/*.jsx"
|
|
5
|
+
- "**/components/**/*.ts"
|
|
6
|
+
- "**/app/**/*.ts"
|
|
7
|
+
- "**/pages/**/*.ts"
|
|
8
|
+
---
|
|
9
|
+
# React Security
|
|
10
|
+
|
|
11
|
+
> This file extends the upstream `typescript/security.md` and `common/security.md` rules with React specific content.
|
|
12
|
+
|
|
13
|
+
## XSS via `dangerouslySetInnerHTML`
|
|
14
|
+
|
|
15
|
+
CRITICAL. The prop name is deliberately scary — treat every usage as a code review halt.
|
|
16
|
+
|
|
17
|
+
```tsx
|
|
18
|
+
// CRITICAL: unsanitized user input
|
|
19
|
+
<div dangerouslySetInnerHTML={{ __html: userBio }} />
|
|
20
|
+
|
|
21
|
+
// CORRECT options:
|
|
22
|
+
// 1. Render as text
|
|
23
|
+
<div>{userBio}</div>
|
|
24
|
+
|
|
25
|
+
// 2. Render parsed markdown via a library that sanitizes
|
|
26
|
+
<ReactMarkdown>{userBio}</ReactMarkdown>
|
|
27
|
+
|
|
28
|
+
// 3. If raw HTML is required, sanitize first with DOMPurify
|
|
29
|
+
import DOMPurify from "isomorphic-dompurify";
|
|
30
|
+
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userBio) }} />
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Audit checklist for every `dangerouslySetInnerHTML` call:
|
|
34
|
+
|
|
35
|
+
- Is the input always under our control? Document the source.
|
|
36
|
+
- If user-derived: is it sanitized at the **same call site**? (Sanitization at the API boundary is acceptable only if every consumer is verified.)
|
|
37
|
+
- Is the sanitizer config allowlisting tags, not denylisting?
|
|
38
|
+
|
|
39
|
+
## Unsafe URL Schemes
|
|
40
|
+
|
|
41
|
+
`javascript:` and `data:` URLs in `href`, `src`, and `xlink:href` execute arbitrary code.
|
|
42
|
+
|
|
43
|
+
```tsx
|
|
44
|
+
// CRITICAL: javascript: URL injection
|
|
45
|
+
<a href={user.website}>Visit</a> // if user.website = "javascript:alert(1)"
|
|
46
|
+
|
|
47
|
+
// CORRECT: validate scheme
|
|
48
|
+
function safeUrl(url: string): string | undefined {
|
|
49
|
+
try {
|
|
50
|
+
const parsed = new URL(url);
|
|
51
|
+
if (["http:", "https:", "mailto:"].includes(parsed.protocol)) return url;
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
<a href={safeUrl(user.website)}>Visit</a>
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
React warns about `javascript:` URLs in `href` in development mode, but does not block them at runtime. `data:` URLs and other schemes also slip through. Always validate.
|
|
61
|
+
|
|
62
|
+
## `target="_blank"` Without `rel`
|
|
63
|
+
|
|
64
|
+
`<a target="_blank">` without `rel="noopener noreferrer"` lets the target page access `window.opener` and run navigation hijacks.
|
|
65
|
+
|
|
66
|
+
```tsx
|
|
67
|
+
// WRONG
|
|
68
|
+
<a href={externalUrl} target="_blank">External</a>
|
|
69
|
+
|
|
70
|
+
// CORRECT
|
|
71
|
+
<a href={externalUrl} target="_blank" rel="noopener noreferrer">External</a>
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Modern browsers default to `noopener` when `target="_blank"`, but do not rely on browser defaults — be explicit.
|
|
75
|
+
|
|
76
|
+
## Server Action Input Validation
|
|
77
|
+
|
|
78
|
+
Server Actions (`"use server"`) run with the same trust level as a public API endpoint. Validate every input.
|
|
79
|
+
|
|
80
|
+
```tsx
|
|
81
|
+
"use server";
|
|
82
|
+
import { z } from "zod";
|
|
83
|
+
|
|
84
|
+
const Input = z.object({
|
|
85
|
+
email: z.string().email(),
|
|
86
|
+
age: z.number().int().min(0).max(120),
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
export async function updateUser(_state: unknown, formData: FormData) {
|
|
90
|
+
const parsed = Input.safeParse({
|
|
91
|
+
email: formData.get("email"),
|
|
92
|
+
age: Number(formData.get("age")),
|
|
93
|
+
});
|
|
94
|
+
if (!parsed.success) return { error: parsed.error.flatten() };
|
|
95
|
+
// ...
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
- Authenticate inside the action — do not trust the client-side route gate
|
|
100
|
+
- Authorize: confirm the current user has permission for the specific record they are mutating
|
|
101
|
+
- Rate limit sensitive actions
|
|
102
|
+
|
|
103
|
+
## Secret Exposure via Env Vars
|
|
104
|
+
|
|
105
|
+
Prefixed env vars are bundled into the client. Treat them as public.
|
|
106
|
+
|
|
107
|
+
| Framework | Public prefix | Private |
|
|
108
|
+
|---|---|---|
|
|
109
|
+
| Next.js | `NEXT_PUBLIC_*` | All others |
|
|
110
|
+
| Vite | `VITE_*` | `.env` server-side only |
|
|
111
|
+
| Create React App | `REACT_APP_*`, plus `NODE_ENV` and `PUBLIC_URL` | All others (anything without the `REACT_APP_` prefix is server-side only) |
|
|
112
|
+
| Remix | `process.env` access in `loader`/`action` only | Same |
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
// CRITICAL: secret leaked to client bundle
|
|
116
|
+
const apiKey = process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY;
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Audit on every PR that touches env vars: would this string in the public bundle be a problem?
|
|
120
|
+
|
|
121
|
+
## Authentication / Authorization
|
|
122
|
+
|
|
123
|
+
- Never store sessions in `localStorage` — accessible to any XSS. Use httpOnly secure cookies.
|
|
124
|
+
- Never trust client-set state to gate sensitive UI. Render-gating in JSX prevents display, not access — the API must enforce.
|
|
125
|
+
- CSRF: cookie-based auth requires CSRF tokens or `SameSite=Strict`/`Lax` cookies
|
|
126
|
+
- Use double-submit cookies or origin verification for form actions when not using framework defaults
|
|
127
|
+
|
|
128
|
+
## Content Security Policy (CSP)
|
|
129
|
+
|
|
130
|
+
Configure server-side. The minimum acceptable CSP for a React app:
|
|
131
|
+
|
|
132
|
+
```
|
|
133
|
+
default-src 'self';
|
|
134
|
+
script-src 'self' 'nonce-{REQUEST_NONCE}';
|
|
135
|
+
style-src 'self' 'unsafe-inline';
|
|
136
|
+
img-src 'self' data: https:;
|
|
137
|
+
connect-src 'self' https://api.example.com;
|
|
138
|
+
frame-ancestors 'none';
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
- Avoid `unsafe-inline` and `unsafe-eval` in `script-src`
|
|
142
|
+
- For SSR with inline scripts (Next.js streaming, hydration data), use per-request nonces — both Next.js and Remix support nonce injection
|
|
143
|
+
- `style-src 'unsafe-inline'` is often unavoidable for CSS-in-JS libraries — document the tradeoff
|
|
144
|
+
|
|
145
|
+
## Prototype Pollution via Object Spread
|
|
146
|
+
|
|
147
|
+
```tsx
|
|
148
|
+
// WRONG: untrusted JSON spread directly into state
|
|
149
|
+
const update = await req.json();
|
|
150
|
+
setState({ ...state, ...update }); // attacker controls __proto__
|
|
151
|
+
|
|
152
|
+
// CORRECT: parse with a schema, or guard keys
|
|
153
|
+
const Allowed = z.object({ name: z.string(), email: z.string().email() });
|
|
154
|
+
const parsed = Allowed.parse(await req.json());
|
|
155
|
+
setState({ ...state, ...parsed });
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## SSR Template Injection
|
|
159
|
+
|
|
160
|
+
When using `renderToString` or `renderToPipeableStream`:
|
|
161
|
+
|
|
162
|
+
- All values rendered inside JSX are escaped by React — safe
|
|
163
|
+
- Values passed to `dangerouslySetInnerHTML` are NOT escaped — same rules as client
|
|
164
|
+
- Manually constructed HTML wrappers around the React output must be escaped or sanitized — never concatenate user input into the surrounding HTML template
|
|
165
|
+
|
|
166
|
+
## Third-Party Components
|
|
167
|
+
|
|
168
|
+
- Audit `npm audit` before adding any UI library
|
|
169
|
+
- Check that the library does not internally use `dangerouslySetInnerHTML` on its input (e.g., rich text editors)
|
|
170
|
+
- Pin versions, review changelogs before major upgrades
|
|
171
|
+
- Be wary of components that accept HTML strings as props
|
|
172
|
+
|
|
173
|
+
## Source Map Exposure in Production
|
|
174
|
+
|
|
175
|
+
Production builds should ship without source maps, or with sourcemaps uploaded to an error tracker (Sentry) and stripped from the public bundle. Public source maps leak internal logic and file structure.
|
|
176
|
+
|
|
177
|
+
## Agent Support
|
|
178
|
+
|
|
179
|
+
- Use `security-reviewer` agent for comprehensive security audits across the codebase
|
|
180
|
+
- Use `react-reviewer` agent for React-specific patterns and the above rules in active code review
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
---
|
|
2
|
+
paths:
|
|
3
|
+
- "**/*.test.tsx"
|
|
4
|
+
- "**/*.test.jsx"
|
|
5
|
+
- "**/*.spec.tsx"
|
|
6
|
+
- "**/*.spec.jsx"
|
|
7
|
+
- "**/__tests__/**/*.ts"
|
|
8
|
+
- "**/__tests__/**/*.tsx"
|
|
9
|
+
---
|
|
10
|
+
# React Testing
|
|
11
|
+
|
|
12
|
+
> This file extends the upstream `typescript/testing.md` and `common/testing.md` rules with React specific content.
|
|
13
|
+
|
|
14
|
+
## Library Choice
|
|
15
|
+
|
|
16
|
+
- **React Testing Library (RTL)** — the standard for component testing. Tests behavior through the rendered DOM.
|
|
17
|
+
- **Vitest** — preferred runner for new Vite-based projects. Faster than Jest, native ESM, same API.
|
|
18
|
+
- **Jest** — still the default for Next.js / CRA projects. RTL works identically.
|
|
19
|
+
- **Playwright Component Testing** — when component tests need a real browser engine (animation, layout, complex events)
|
|
20
|
+
- **Cypress Component Testing** — alternative real-browser component runner
|
|
21
|
+
|
|
22
|
+
Pick one component test runner per project — do not mix RTL + Playwright CT in the same repo.
|
|
23
|
+
|
|
24
|
+
## Core Principle
|
|
25
|
+
|
|
26
|
+
Test what the user sees and does, not implementation details.
|
|
27
|
+
|
|
28
|
+
- Query by accessible role first, then label, then text — fall back to `data-testid` only when nothing else fits
|
|
29
|
+
- Never assert on internal state, props passed to children, or which hooks were called
|
|
30
|
+
- Refactor without breaking tests = the test was testing behavior; that is the goal
|
|
31
|
+
|
|
32
|
+
## Query Priority
|
|
33
|
+
|
|
34
|
+
RTL exposes queries in three families. Use this priority order top-down:
|
|
35
|
+
|
|
36
|
+
1. **Accessible to everyone**
|
|
37
|
+
- `getByRole(role, { name })` — primary choice
|
|
38
|
+
- `getByLabelText` — for form inputs
|
|
39
|
+
- `getByPlaceholderText` — when no label is available (and add a label)
|
|
40
|
+
- `getByText` — for non-interactive text
|
|
41
|
+
- `getByDisplayValue` — for form fields with a current value
|
|
42
|
+
|
|
43
|
+
2. **Semantic queries**
|
|
44
|
+
- `getByAltText` — for images
|
|
45
|
+
- `getByTitle` — last resort, low accessibility value
|
|
46
|
+
|
|
47
|
+
3. **Test IDs**
|
|
48
|
+
- `getByTestId("some-id")` — escape hatch only, when none of the above work
|
|
49
|
+
|
|
50
|
+
`getBy*` throws when no match. `queryBy*` returns null (use for asserting absence). `findBy*` returns a promise (use for async).
|
|
51
|
+
|
|
52
|
+
## User Interaction
|
|
53
|
+
|
|
54
|
+
Prefer `userEvent` over `fireEvent`. `userEvent` simulates real browser sequences (focus, keydown, beforeinput, input, keyup) — `fireEvent` dispatches a single synthetic event.
|
|
55
|
+
|
|
56
|
+
```tsx
|
|
57
|
+
import userEvent from "@testing-library/user-event";
|
|
58
|
+
|
|
59
|
+
test("submits the form", async () => {
|
|
60
|
+
const user = userEvent.setup();
|
|
61
|
+
render(<UserForm onSubmit={handleSubmit} />);
|
|
62
|
+
|
|
63
|
+
await user.type(screen.getByLabelText("Email"), "user@example.com");
|
|
64
|
+
await user.click(screen.getByRole("button", { name: /save/i }));
|
|
65
|
+
|
|
66
|
+
expect(handleSubmit).toHaveBeenCalledWith({ email: "user@example.com" });
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- Always `await` `userEvent` calls — they are async
|
|
71
|
+
- Call `userEvent.setup()` once at the top of each test, then reuse the returned `user`
|
|
72
|
+
|
|
73
|
+
## Async Assertions
|
|
74
|
+
|
|
75
|
+
```tsx
|
|
76
|
+
// WRONG: synchronous query for async-rendered content
|
|
77
|
+
expect(screen.getByText("Loaded")).toBeInTheDocument(); // throws — not in DOM yet
|
|
78
|
+
|
|
79
|
+
// CORRECT: findBy* (returns a promise, retries)
|
|
80
|
+
expect(await screen.findByText("Loaded")).toBeInTheDocument();
|
|
81
|
+
|
|
82
|
+
// CORRECT: waitFor for non-element assertions
|
|
83
|
+
await waitFor(() => expect(saveSpy).toHaveBeenCalled());
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
- `findBy*` for async element appearance
|
|
87
|
+
- `waitFor` for async expectations on side effects or other matchers
|
|
88
|
+
- Never `setTimeout` + assertion — flaky
|
|
89
|
+
|
|
90
|
+
## Network Mocking with MSW
|
|
91
|
+
|
|
92
|
+
Use Mock Service Worker for any test that hits a network boundary. MSW runs at the network layer, so the component, hooks, and fetch library all behave as in production.
|
|
93
|
+
|
|
94
|
+
```tsx
|
|
95
|
+
// test setup
|
|
96
|
+
import { setupServer } from "msw/node";
|
|
97
|
+
import { http, HttpResponse } from "msw";
|
|
98
|
+
|
|
99
|
+
const server = setupServer(
|
|
100
|
+
http.get("/api/users/:id", ({ params }) =>
|
|
101
|
+
HttpResponse.json({ id: params.id, name: "Alice" }),
|
|
102
|
+
),
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
beforeAll(() => server.listen());
|
|
106
|
+
afterEach(() => server.resetHandlers());
|
|
107
|
+
afterAll(() => server.close());
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Per-test override:
|
|
111
|
+
|
|
112
|
+
```tsx
|
|
113
|
+
test("renders error on 500", async () => {
|
|
114
|
+
server.use(http.get("/api/users/:id", () => new HttpResponse(null, { status: 500 })));
|
|
115
|
+
render(<UserPage id="1" />);
|
|
116
|
+
expect(await screen.findByText(/something went wrong/i)).toBeInTheDocument();
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Avoid Snapshot Tests for Components
|
|
121
|
+
|
|
122
|
+
Snapshots of rendered output are brittle, hard to review, and rubber-stamped by reviewers. Use them only for:
|
|
123
|
+
|
|
124
|
+
- Pure data serialization (e.g., a transformer that produces a stable string)
|
|
125
|
+
- Catching unintended regressions in non-visual output
|
|
126
|
+
|
|
127
|
+
For component visual regression, use Playwright / Cypress / Percy screenshots — actual visual diffs, not DOM diffs.
|
|
128
|
+
|
|
129
|
+
## Test Setup Helpers
|
|
130
|
+
|
|
131
|
+
Wrap providers once:
|
|
132
|
+
|
|
133
|
+
```tsx
|
|
134
|
+
function renderWithProviders(ui: React.ReactElement) {
|
|
135
|
+
return render(
|
|
136
|
+
<QueryClientProvider client={new QueryClient()}>
|
|
137
|
+
<ThemeProvider theme={lightTheme}>
|
|
138
|
+
<Router>{ui}</Router>
|
|
139
|
+
</ThemeProvider>
|
|
140
|
+
</QueryClientProvider>,
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Export from `test-utils.tsx` and use everywhere.
|
|
146
|
+
|
|
147
|
+
## Custom Hook Testing
|
|
148
|
+
|
|
149
|
+
Use `renderHook` from RTL:
|
|
150
|
+
|
|
151
|
+
```tsx
|
|
152
|
+
import { renderHook, act } from "@testing-library/react";
|
|
153
|
+
|
|
154
|
+
test("useCounter increments", () => {
|
|
155
|
+
const { result } = renderHook(() => useCounter());
|
|
156
|
+
act(() => result.current.increment());
|
|
157
|
+
expect(result.current.count).toBe(1);
|
|
158
|
+
});
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
- Always wrap state-changing calls in `act`
|
|
162
|
+
- Always test through the public hook API, not internal implementation
|
|
163
|
+
|
|
164
|
+
## Accessibility Assertions
|
|
165
|
+
|
|
166
|
+
```tsx
|
|
167
|
+
import { axe } from "vitest-axe"; // or jest-axe
|
|
168
|
+
|
|
169
|
+
test("UserCard has no a11y violations", async () => {
|
|
170
|
+
const { container } = render(<UserCard user={mockUser} />);
|
|
171
|
+
expect(await axe(container)).toHaveNoViolations();
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Run axe assertions in component tests — catches missing labels, ARIA misuse, color contrast (limited).
|
|
176
|
+
|
|
177
|
+
## When to Reach for Playwright / Cypress
|
|
178
|
+
|
|
179
|
+
Component test with RTL + JSDOM cannot:
|
|
180
|
+
|
|
181
|
+
- Test real layout (flexbox, grid, viewport-dependent rendering)
|
|
182
|
+
- Test scrolling, drag-and-drop, paste from clipboard
|
|
183
|
+
- Test browser-native animation, CSS transitions
|
|
184
|
+
- Test cross-frame interactions (iframes, popups)
|
|
185
|
+
|
|
186
|
+
For those, use Playwright Component Testing or end-to-end Playwright/Cypress runs. See the e2e-testing skill when it is installed.
|
|
187
|
+
|
|
188
|
+
## Coverage Targets
|
|
189
|
+
|
|
190
|
+
| Layer | Target |
|
|
191
|
+
|---|---|
|
|
192
|
+
| Pure utility functions | ≥90% |
|
|
193
|
+
| Custom hooks | ≥85% |
|
|
194
|
+
| Components (presentational) | ≥80% — behavior, not lines |
|
|
195
|
+
| Container components | ≥70% — golden paths + error states |
|
|
196
|
+
| Pages (E2E covered separately) | Smoke test per route minimum |
|
|
197
|
+
|
|
198
|
+
## Anti-Patterns
|
|
199
|
+
|
|
200
|
+
- Asserting on `container.querySelector` — bypasses accessibility queries
|
|
201
|
+
- Asserting on number of renders — implementation detail
|
|
202
|
+
- Mocking React hooks (`jest.mock("react", ...)`) — refactor the component instead
|
|
203
|
+
- Mocking child components by default — tests the integration, not the parent in isolation
|
|
204
|
+
- Manual `act()` warnings ignored — they indicate real bugs
|
|
205
|
+
|
|
206
|
+
## Skill Reference
|
|
207
|
+
|
|
208
|
+
See `skills/react-testing/SKILL.md` for end-to-end test examples, MSW patterns, and accessibility test scaffolding.
|
|
@@ -243,7 +243,7 @@ Run axe in component tests for every interactive component. Catches:
|
|
|
243
243
|
- Missing alt text on images
|
|
244
244
|
- Heading order violations
|
|
245
245
|
|
|
246
|
-
Cross-link:
|
|
246
|
+
Cross-link: skills/accessibility for the broader a11y testing playbook when that optional skill is installed.
|
|
247
247
|
|
|
248
248
|
## When NOT to Use Snapshot Tests
|
|
249
249
|
|
|
@@ -270,7 +270,7 @@ JSDOM (used by Vitest/Jest) cannot:
|
|
|
270
270
|
- Handle iframes, popups, downloads, cross-origin flows
|
|
271
271
|
- Run real network in a controlled environment with full DevTools support
|
|
272
272
|
|
|
273
|
-
For any of those, use Playwright Component Testing (component test in real browser) or full E2E. See
|
|
273
|
+
For any of those, use Playwright Component Testing (component test in real browser) or full E2E. See the e2e-testing skill when it is installed.
|
|
274
274
|
|
|
275
275
|
Decision boundary:
|
|
276
276
|
|
|
@@ -354,8 +354,8 @@ CI=true vitest run --coverage
|
|
|
354
354
|
|
|
355
355
|
## Related
|
|
356
356
|
|
|
357
|
-
- Rules: [rules/react/testing.md](
|
|
358
|
-
- Skills: [react-patterns](../react-patterns/SKILL.md),
|
|
357
|
+
- Rules: [rules/react/testing.md](rules/react/testing.md)
|
|
358
|
+
- Skills: [react-patterns](../react-patterns/SKILL.md), accessibility, e2e-testing, tdd-workflow
|
|
359
359
|
- Agents: `react-reviewer` (reviews test quality during code review), `tdd-guide` (enforces TDD process)
|
|
360
360
|
- Commands: `/react-test`, `/react-review`
|
|
361
361
|
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Affaan Mustafa
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Third-party notice
|
|
2
|
+
|
|
3
|
+
This directory contains React rule references copied from Affaan Mustafa's ECC
|
|
4
|
+
repository.
|
|
5
|
+
|
|
6
|
+
- Source: https://github.com/affaan-m/ECC/tree/main/rules/react
|
|
7
|
+
- Source commit: 0f84c0e2796703fbda87d577b2636351418c7442
|
|
8
|
+
- License: MIT
|
|
9
|
+
- Copyright: Copyright (c) 2026 Affaan Mustafa
|
|
10
|
+
|
|
11
|
+
The upstream MIT license is included in `LICENSE`.
|