@polymorphism-tech/morph-spec 7.0.0 → 7.1.0

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.
Files changed (79) hide show
  1. package/README.md +367 -367
  2. package/framework/agents.json +132 -127
  3. package/framework/rubrics/backend.json +41 -36
  4. package/framework/rules/ai-agents-standards.md +45 -15
  5. package/framework/rules/neon-standards.md +25 -26
  6. package/framework/standards/STANDARDS.json +1729 -1133
  7. package/framework/standards/ai-agents/agent-session.md +160 -0
  8. package/framework/standards/ai-agents/batching.md +193 -0
  9. package/framework/standards/ai-agents/context-providers.md +188 -0
  10. package/framework/standards/ai-agents/mcp-server.md +250 -0
  11. package/framework/standards/ai-agents/mcp-tools.md +197 -0
  12. package/framework/standards/ai-agents/middleware-patterns.md +207 -0
  13. package/framework/standards/ai-agents/modalities-image-gen.md +173 -0
  14. package/framework/standards/ai-agents/modalities-speech-to-text.md +171 -0
  15. package/framework/standards/ai-agents/modalities-text-to-speech.md +181 -0
  16. package/framework/standards/ai-agents/modalities-vision.md +201 -0
  17. package/framework/standards/ai-agents/multi-agent-patterns.md +155 -0
  18. package/framework/standards/ai-agents/production.md +114 -258
  19. package/framework/standards/ai-agents/prompts-in-db.md +214 -0
  20. package/framework/standards/ai-agents/providers/model-registry.md +158 -0
  21. package/framework/standards/ai-agents/rag-custom-pgvector.md +243 -0
  22. package/framework/standards/ai-agents/service-tier-flex.md +135 -0
  23. package/framework/standards/ai-agents/setup.md +142 -316
  24. package/framework/standards/ai-agents/structured-output.md +249 -0
  25. package/framework/standards/ai-agents/sweet-spot.md +109 -0
  26. package/framework/standards/ai-agents/workflows.md +114 -284
  27. package/framework/standards/architecture/vertical-slice/vertical-slice.md +433 -429
  28. package/framework/standards/backend/api/validation.md +92 -88
  29. package/framework/standards/backend/database/postgresql/database.md +336 -332
  30. package/framework/standards/backend/database/vector-search-rag.md +599 -541
  31. package/framework/standards/backend/dotnet/fluent-validation-vsa.md +4 -0
  32. package/framework/standards/backend/dotnet/result-pattern.md +4 -0
  33. package/framework/standards/backend/dotnet/scalar-ui.md +176 -172
  34. package/framework/standards/backend/dotnet/scrutor.md +4 -0
  35. package/framework/standards/backend/dotnet/vsa-handler-patterns.md +278 -274
  36. package/framework/standards/backend/integrations/asaas/asaas-api.md +260 -216
  37. package/framework/standards/backend/integrations/hangfire/hangfire-jobs.md +354 -350
  38. package/framework/standards/backend/integrations/neon-auth/neon-auth.md +30 -19
  39. package/framework/standards/backend/integrations/resend/resend-email.md +400 -385
  40. package/framework/standards/data/nosql/cache/redis.md +106 -97
  41. package/framework/standards/data/nosql/cosmos-db.md +127 -118
  42. package/framework/standards/data/vector-search/rag-chunking.md +113 -104
  43. package/framework/standards/frontend/design-system/ai-image-generation.md +4 -0
  44. package/framework/standards/frontend/design-system/animations.md +164 -160
  45. package/framework/standards/frontend/design-system/naming.md +68 -64
  46. package/framework/standards/frontend/gsap/gsap-core.md +14 -8
  47. package/framework/standards/frontend/gsap/gsap-plugins.md +26 -21
  48. package/framework/standards/frontend/gsap/gsap-scrolltrigger.md +9 -7
  49. package/framework/standards/frontend/nextjs/app-router.md +127 -123
  50. package/framework/standards/frontend/nextjs/components.md +136 -132
  51. package/framework/standards/frontend/nextjs/data-fetching.md +130 -126
  52. package/framework/standards/frontend/nextjs/forms.md +134 -128
  53. package/framework/standards/frontend/nextjs/motion-patterns.md +328 -322
  54. package/framework/standards/frontend/nextjs/naming-conventions.md +71 -67
  55. package/framework/standards/frontend/nextjs/nextjs-patterns.md +229 -225
  56. package/framework/standards/frontend/nextjs/project-structure.md +106 -102
  57. package/framework/standards/frontend/nextjs/state-management.md +76 -72
  58. package/framework/standards/frontend/nextjs/testing.md +115 -111
  59. package/framework/standards/infrastructure/docker/easypanel-deploy.md +196 -192
  60. package/framework/standards/infrastructure/neon/neon-pgrag.md +6 -2
  61. package/framework/standards/infrastructure/neon/neon-pgvector.md +4 -0
  62. package/framework/standards/infrastructure/neon/neon-setup.md +5 -1
  63. package/framework/standards/integration/mcp/mcp-tools.md +471 -462
  64. package/framework/templates/REGISTRY.json +1745 -1239
  65. package/framework/templates/code/dotnet/ai-agents/AgentBootstrap.cs.template +39 -0
  66. package/framework/templates/code/dotnet/ai-agents/EmbeddingService.cs.template +68 -0
  67. package/framework/templates/code/dotnet/ai-agents/ModelRegistry.cs.template +117 -0
  68. package/framework/templates/code/dotnet/ai-agents/PromptRepository.cs.template +95 -0
  69. package/framework/templates/code/dotnet/ai-agents/ResilientToolMiddleware.cs.template +61 -0
  70. package/framework/templates/code/dotnet/ai-agents/VectorSearchTool.cs.template +107 -0
  71. package/framework/templates/code/dotnet/ai-agents/model-registry.json.template +58 -0
  72. package/framework/templates/code/sql/ai-agents/agent-prompts-migration.sql.template +58 -0
  73. package/framework/templates/code/sql/ai-agents/pgvector-embeddings-migration.sql.template +91 -0
  74. package/package.json +89 -83
  75. package/src/core/templates/template-registry.js +289 -256
  76. package/src/lib/generators/context-generator.js +516 -518
  77. package/src/lib/generators/scaffold-generator.js +23 -26
  78. package/framework/standards/infrastructure/neon/neon-semantic-kernel.md +0 -310
  79. package/framework/templates/integrations/semantic-kernel-neon.cs +0 -125
@@ -1,102 +1,106 @@
1
- # Next.js Project Structure Standard
2
-
3
- > **Scope:** frontend/nextjs/project-structure
4
- > **Layer:** 2 (on keyword)
5
- > **Keywords:** project structure, folder structure, feature folder, src layout
6
- > **Load When:** creating new files or features
7
-
8
- Feature-based architecture with a shared core. Features are self-contained; shared code is explicit.
9
-
10
- ## Core Rules
11
-
12
- - ALWAYS use feature-based folders: `features/{feature-name}/`
13
- - ALWAYS keep `app/` for routing only — import from `features/`, not the other way
14
- - NEVER import from one feature into another — extract to `components/` or `lib/` if shared
15
- - ALWAYS use `src/` directory (configured in `tsconfig.json` with `@/` alias)
16
- - NEVER put business logic in `components/` — it is presentation only
17
-
18
- ## Canonical Folder Tree
19
-
20
- ```
21
- src/
22
- ├── app/ # Next.js App Router — routes only
23
- │ ├── layout.tsx # Root layout + providers
24
- │ ├── page.tsx # Home page
25
- │ └── (dashboard)/
26
- │ ├── layout.tsx
27
- │ ├── users/
28
- │ │ ├── page.tsx
29
- │ │ ├── loading.tsx
30
- │ │ └── error.tsx
31
- │ └── billing/
32
- │ └── page.tsx
33
- │
34
- ├── features/ # Domain features
35
- │ └── {feature-name}/
36
- │ ├── components/ # Feature-specific UI components
37
- │ │ ├── user-list.tsx
38
- │ │ └── user-card.tsx
39
- │ ├── hooks/ # TanStack Query hooks for this feature
40
- │ │ ├── use-users.ts
41
- │ │ └── use-create-user.ts
42
- │ ├── types/
43
- │ │ ├── user.types.ts # TypeScript types
44
- │ │ └── user.schemas.ts # Zod schemas + z.infer<> types
45
- │ └── index.ts # Public API — only export what's needed
46
- │
47
- ├── components/ # Shared UI — no business logic
48
- │ ├── ui/ # shadcn/ui — never edit directly
49
- │ │ ├── button.tsx
50
- │ │ └── card.tsx
51
- │ ├── data-table.tsx
52
- │ ├── page-header.tsx
53
- │ └── empty-state.tsx
54
- │
55
- ├── hooks/ # Shared utility hooks — no API calls
56
- │ ├── use-debounce.ts
57
- │ └── use-media-query.ts
58
- │
59
- ├── lib/
60
- │ ├── api-client.ts # Typed fetch wrapper for .NET API
61
- │ └── query-client.tsx # TanStack Query client + provider
62
- │
63
- ├── types/
64
- │ ├── api.ts # Shared API shapes: PaginatedResponse<T>, ApiError
65
- │ └── env.d.ts
66
- │
67
- └── env.mjs # Zod-validated env vars
68
- ```
69
-
70
- ## Feature Index Pattern
71
-
72
- ```ts
73
- // features/users/index.ts — explicit public API
74
- export { UserList } from './components/user-list';
75
- export { UserCard } from './components/user-card';
76
- export { useUsers } from './hooks/use-users';
77
- export { useCreateUser } from './hooks/use-create-user';
78
- export type { User, CreateUserInput } from './types/user.types';
79
- ```
80
-
81
- Import from the index, not deep paths:
82
- ```ts
83
- // GOOD
84
- import { UserList, useUsers } from '@/features/users';
85
-
86
- // BAD
87
- import { UserList } from '@/features/users/components/user-list';
88
- ```
89
-
90
- ## Feature Boundary Rule
91
-
92
- ```
93
- app/ → imports from features/ ✓
94
- features/users/ → imports from components/ and lib/ ✓
95
- features/users/ → imports from features/billing/ ✗ (extract shared instead)
96
- components/ → imports from components/ui/ ✓
97
- components/ → imports from features/ ✗
98
- ```
99
-
100
- ---
101
-
102
- *MORPH-SPEC by Polymorphism Tech*
1
+ # Next.js Project Structure Standard
2
+
3
+ > **Scope:** frontend/nextjs/project-structure
4
+ > **Layer:** 2 (on keyword)
5
+ > **Keywords:** project structure, folder structure, feature folder, src layout
6
+ > **Load When:** creating new files or features
7
+
8
+ **Verified against:** Next.js 15 (App Router, `src/` layout). Last-verified: 2026-05-20.
9
+
10
+ ---
11
+
12
+ Feature-based architecture with a shared core. Features are self-contained; shared code is explicit.
13
+
14
+ ## Core Rules
15
+
16
+ - ALWAYS use feature-based folders: `features/{feature-name}/`
17
+ - ALWAYS keep `app/` for routing only — import from `features/`, not the other way
18
+ - NEVER import from one feature into another — extract to `components/` or `lib/` if shared
19
+ - ALWAYS use `src/` directory (configured in `tsconfig.json` with `@/` alias)
20
+ - NEVER put business logic in `components/` — it is presentation only
21
+
22
+ ## Canonical Folder Tree
23
+
24
+ ```
25
+ src/
26
+ ├── app/ # Next.js App Router — routes only
27
+ │ ├── layout.tsx # Root layout + providers
28
+ │ ├── page.tsx # Home page
29
+ │ └── (dashboard)/
30
+ │ ├── layout.tsx
31
+ │ ├── users/
32
+ │ │ ├── page.tsx
33
+ │ │ ├── loading.tsx
34
+ │ │ └── error.tsx
35
+ │ └── billing/
36
+ │ └── page.tsx
37
+ │
38
+ ├── features/ # Domain features
39
+ │ └── {feature-name}/
40
+ │ ├── components/ # Feature-specific UI components
41
+ │ │ ├── user-list.tsx
42
+ │ │ └── user-card.tsx
43
+ │ ├── hooks/ # TanStack Query hooks for this feature
44
+ │ │ ├── use-users.ts
45
+ │ │ └── use-create-user.ts
46
+ │ ├── types/
47
+ │ │ ├── user.types.ts # TypeScript types
48
+ │ │ └── user.schemas.ts # Zod schemas + z.infer<> types
49
+ │ └── index.ts # Public API — only export what's needed
50
+ │
51
+ ├── components/ # Shared UI — no business logic
52
+ │ ├── ui/ # shadcn/ui — never edit directly
53
+ │ │ ├── button.tsx
54
+ │ │ └── card.tsx
55
+ │ ├── data-table.tsx
56
+ │ ├── page-header.tsx
57
+ │ └── empty-state.tsx
58
+ │
59
+ ├── hooks/ # Shared utility hooks — no API calls
60
+ │ ├── use-debounce.ts
61
+ │ └── use-media-query.ts
62
+ │
63
+ ├── lib/
64
+ │ ├── api-client.ts # Typed fetch wrapper for .NET API
65
+ │ └── query-client.tsx # TanStack Query client + provider
66
+ │
67
+ ├── types/
68
+ │ ├── api.ts # Shared API shapes: PaginatedResponse<T>, ApiError
69
+ │ └── env.d.ts
70
+ │
71
+ └── env.mjs # Zod-validated env vars
72
+ ```
73
+
74
+ ## Feature Index Pattern
75
+
76
+ ```ts
77
+ // features/users/index.ts — explicit public API
78
+ export { UserList } from './components/user-list';
79
+ export { UserCard } from './components/user-card';
80
+ export { useUsers } from './hooks/use-users';
81
+ export { useCreateUser } from './hooks/use-create-user';
82
+ export type { User, CreateUserInput } from './types/user.types';
83
+ ```
84
+
85
+ Import from the index, not deep paths:
86
+ ```ts
87
+ // GOOD
88
+ import { UserList, useUsers } from '@/features/users';
89
+
90
+ // BAD
91
+ import { UserList } from '@/features/users/components/user-list';
92
+ ```
93
+
94
+ ## Feature Boundary Rule
95
+
96
+ ```
97
+ app/ → imports from features/ ✓
98
+ features/users/ → imports from components/ and lib/ ✓
99
+ features/users/ → imports from features/billing/ ✗ (extract shared instead)
100
+ components/ → imports from components/ui/ ✓
101
+ components/ → imports from features/ ✗
102
+ ```
103
+
104
+ ---
105
+
106
+ *MORPH-SPEC by Polymorphism Tech*
@@ -1,72 +1,76 @@
1
- # Next.js State Management Standard
2
-
3
- > **Scope:** frontend/nextjs/state-management
4
- > **Layer:** 2 (on keyword)
5
- > **Keywords:** state, zustand, context, redux, client state, server state, useState
6
- > **Load When:** deciding how to manage state in Next.js
7
-
8
- Server state (API data) lives in TanStack Query. UI state lives in React. No global state library unless genuinely needed.
9
-
10
- ## Core Rules
11
-
12
- - ALWAYS use TanStack Query for anything that comes from the .NET API
13
- - ALWAYS use `useState` for local UI state (modal open, selected tab, form step)
14
- - NEVER install Zustand or Redux without first exhausting Server Components + TanStack Query
15
- - NEVER use React Context for server state — Context does not cache or deduplicate
16
- - ALWAYS derive state from server data rather than syncing it to local state
17
-
18
- ## State Decision Tree
19
-
20
- ```
21
- Is this data from the .NET API?
22
- YES → TanStack Query (useQuery / useMutation)
23
-
24
- Is this local UI state (open/closed, selected, current step)?
25
- YES → useState in the component that needs it
26
-
27
- Does multiple components need this UI state?
28
- YES — is it parent-child? → prop drilling (2-3 levels is fine)
29
- YES — is it truly global? → React Context (theme, auth user, locale)
30
- YES — complex with many actions? → Consider Zustand (last resort)
31
- ```
32
-
33
- ## Server State (TanStack Query)
34
-
35
- ```ts
36
- // GOOD — server state in TanStack Query
37
- const { data: users } = useUsers(); // cached, deduplicated, background-refetched
38
-
39
- // BAD — copying server state to useState
40
- const [users, setUsers] = useState([]);
41
- useEffect(() => { fetchUsers().then(setUsers); }, []);
42
- ```
43
-
44
- ## Local UI State (useState)
45
-
46
- ```tsx
47
- function UserList() {
48
- const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
49
- const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
50
- }
51
- ```
52
-
53
- ## When Zustand Is Justified
54
-
55
- Only add Zustand if ALL of these are true:
56
- 1. State is needed in 5+ unrelated components
57
- 2. State has complex update logic (not just toggle/set)
58
- 3. Context causes measurable re-render performance issues
59
- 4. State is not from the server
60
-
61
- ## Common Mistakes
62
-
63
- | Wrong | Right | Why |
64
- |-------|-------|-----|
65
- | `useEffect` + `useState` for API data | TanStack Query | Stale data, no cache, double-render |
66
- | Global store for user list | `useUsers()` | TanStack Query handles sync/cache |
67
- | Context for everything | useState + prop drilling first | Context causes all consumers to re-render |
68
- | Zustand by default | Start with useState | YAGNI — most state is local |
69
-
70
- ---
71
-
72
- *MORPH-SPEC by Polymorphism Tech*
1
+ # Next.js State Management Standard
2
+
3
+ > **Scope:** frontend/nextjs/state-management
4
+ > **Layer:** 2 (on keyword)
5
+ > **Keywords:** state, zustand, context, redux, client state, server state, useState
6
+ > **Load When:** deciding how to manage state in Next.js
7
+
8
+ **Verified against:** Next.js 15 + TanStack Query 5 + Zustand 5. Last-verified: 2026-05-20.
9
+
10
+ ---
11
+
12
+ Server state (API data) lives in TanStack Query. UI state lives in React. No global state library unless genuinely needed.
13
+
14
+ ## Core Rules
15
+
16
+ - ALWAYS use TanStack Query for anything that comes from the .NET API
17
+ - ALWAYS use `useState` for local UI state (modal open, selected tab, form step)
18
+ - NEVER install Zustand or Redux without first exhausting Server Components + TanStack Query
19
+ - NEVER use React Context for server state — Context does not cache or deduplicate
20
+ - ALWAYS derive state from server data rather than syncing it to local state
21
+
22
+ ## State Decision Tree
23
+
24
+ ```
25
+ Is this data from the .NET API?
26
+ YES → TanStack Query (useQuery / useMutation)
27
+
28
+ Is this local UI state (open/closed, selected, current step)?
29
+ YES → useState in the component that needs it
30
+
31
+ Does multiple components need this UI state?
32
+ YES — is it parent-child? → prop drilling (2-3 levels is fine)
33
+ YES — is it truly global? → React Context (theme, auth user, locale)
34
+ YES — complex with many actions? → Consider Zustand (last resort)
35
+ ```
36
+
37
+ ## Server State (TanStack Query)
38
+
39
+ ```ts
40
+ // GOOD — server state in TanStack Query
41
+ const { data: users } = useUsers(); // cached, deduplicated, background-refetched
42
+
43
+ // BAD — copying server state to useState
44
+ const [users, setUsers] = useState([]);
45
+ useEffect(() => { fetchUsers().then(setUsers); }, []);
46
+ ```
47
+
48
+ ## Local UI State (useState)
49
+
50
+ ```tsx
51
+ function UserList() {
52
+ const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
53
+ const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
54
+ }
55
+ ```
56
+
57
+ ## When Zustand Is Justified
58
+
59
+ Only add Zustand if ALL of these are true:
60
+ 1. State is needed in 5+ unrelated components
61
+ 2. State has complex update logic (not just toggle/set)
62
+ 3. Context causes measurable re-render performance issues
63
+ 4. State is not from the server
64
+
65
+ ## Common Mistakes
66
+
67
+ | Wrong | Right | Why |
68
+ |-------|-------|-----|
69
+ | `useEffect` + `useState` for API data | TanStack Query | Stale data, no cache, double-render |
70
+ | Global store for user list | `useUsers()` | TanStack Query handles sync/cache |
71
+ | Context for everything | useState + prop drilling first | Context causes all consumers to re-render |
72
+ | Zustand by default | Start with useState | YAGNI — most state is local |
73
+
74
+ ---
75
+
76
+ *MORPH-SPEC by Polymorphism Tech*
@@ -1,111 +1,115 @@
1
- # Next.js Testing Standard
2
-
3
- > **Scope:** frontend/nextjs/testing
4
- > **Layer:** 2 (on keyword)
5
- > **Keywords:** testing, jest, vitest, testing-library, msw, component test, unit test
6
- > **Load When:** writing tests for Next.js components or hooks
7
-
8
- Jest + React Testing Library for component tests. MSW for API mocking. Co-locate tests with the code they test.
9
-
10
- ## Core Rules
11
-
12
- - ALWAYS co-locate test files: `user-card.test.tsx` next to `user-card.tsx`
13
- - ALWAYS use `@testing-library/user-event` for interactions — not `fireEvent`
14
- - ALWAYS mock the API layer with MSW — never mock `fetch` directly
15
- - NEVER test implementation details — test what the user sees
16
- - ALWAYS test the happy path + one error path per component
17
-
18
- ## Test File Co-location
19
-
20
- ```
21
- features/users/
22
- ├── components/
23
- │ ├── user-card.tsx
24
- │ ├── user-card.test.tsx ← co-located
25
- │ ├── user-list.tsx
26
- │ └── user-list.test.tsx
27
- ├── hooks/
28
- │ ├── use-users.ts
29
- │ └── use-users.test.ts ← co-located
30
- ```
31
-
32
- ## Component Test Pattern
33
-
34
- ```tsx
35
- // features/users/components/user-card.test.tsx
36
- import { render, screen } from '@testing-library/react';
37
- import userEvent from '@testing-library/user-event';
38
- import { UserCard } from './user-card';
39
-
40
- const mockUser = { id: '1', name: 'João Silva', email: 'joao@example.com', role: 'user' as const };
41
-
42
- describe('UserCard', () => {
43
- it('renders user name and email', () => {
44
- render(<UserCard user={mockUser} />);
45
- expect(screen.getByText('João Silva')).toBeInTheDocument();
46
- expect(screen.getByText('joao@example.com')).toBeInTheDocument();
47
- });
48
-
49
- it('calls onEdit with user id when edit button clicked', async () => {
50
- const onEdit = vi.fn();
51
- render(<UserCard user={mockUser} onEdit={onEdit} />);
52
- await userEvent.click(screen.getByRole('button', { name: /edit/i }));
53
- expect(onEdit).toHaveBeenCalledWith('1');
54
- });
55
- });
56
- ```
57
-
58
- ## Hook Test with MSW
59
-
60
- ```ts
61
- // features/users/hooks/use-users.test.ts
62
- import { renderHook, waitFor } from '@testing-library/react';
63
- import { http, HttpResponse } from 'msw';
64
- import { server } from '@/test/msw-server';
65
- import { QueryClientWrapper } from '@/test/helpers';
66
- import { useUsers } from './use-users';
67
-
68
- describe('useUsers', () => {
69
- it('returns users from API', async () => {
70
- server.use(
71
- http.get('/api/proxy/users', () =>
72
- HttpResponse.json([{ id: '1', name: 'João', email: 'j@ex.com' }])
73
- )
74
- );
75
- const { result } = renderHook(() => useUsers(), { wrapper: QueryClientWrapper });
76
- await waitFor(() => expect(result.current.isSuccess).toBe(true));
77
- expect(result.current.data).toHaveLength(1);
78
- });
79
-
80
- it('returns error state when API fails', async () => {
81
- server.use(http.get('/api/proxy/users', () => new HttpResponse(null, { status: 500 })));
82
- const { result } = renderHook(() => useUsers(), { wrapper: QueryClientWrapper });
83
- await waitFor(() => expect(result.current.isError).toBe(true));
84
- });
85
- });
86
- ```
87
-
88
- ## Test Helper Setup
89
-
90
- ```tsx
91
- // test/helpers.tsx
92
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
93
-
94
- export function QueryClientWrapper({ children }: { children: React.ReactNode }) {
95
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
96
- return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
97
- }
98
- ```
99
-
100
- ## Common Mistakes
101
-
102
- | Wrong | Right | Why |
103
- |-------|-------|-----|
104
- | `fireEvent.click(button)` | `await userEvent.click(button)` | userEvent simulates real browser events |
105
- | Mock `global.fetch` | Mock with MSW | MSW intercepts at network level |
106
- | `expect(component).toMatchSnapshot()` | `expect(screen.getByText(...))` | Snapshots break on any change |
107
- | Test file in `__tests__/` folder | Co-locate with source | Easier to find, deleted with the component |
108
-
109
- ---
110
-
111
- *MORPH-SPEC by Polymorphism Tech*
1
+ # Next.js Testing Standard
2
+
3
+ > **Scope:** frontend/nextjs/testing
4
+ > **Layer:** 2 (on keyword)
5
+ > **Keywords:** testing, vitest, jest, testing-library, msw, component test, unit test
6
+ > **Load When:** writing tests for Next.js components or hooks
7
+
8
+ **Verified against:** Vitest 3 + React Testing Library 16 + MSW 2. Last-verified: 2026-05-20.
9
+
10
+ ---
11
+
12
+ Vitest + React Testing Library for component tests. MSW for API mocking. Co-locate tests with the code they test.
13
+
14
+ ## Core Rules
15
+
16
+ - ALWAYS co-locate test files: `user-card.test.tsx` next to `user-card.tsx`
17
+ - ALWAYS use `@testing-library/user-event` for interactions — not `fireEvent`
18
+ - ALWAYS mock the API layer with MSW — never mock `fetch` directly
19
+ - NEVER test implementation details — test what the user sees
20
+ - ALWAYS test the happy path + one error path per component
21
+
22
+ ## Test File Co-location
23
+
24
+ ```
25
+ features/users/
26
+ ├── components/
27
+ │ ├── user-card.tsx
28
+ │ ├── user-card.test.tsx ← co-located
29
+ │ ├── user-list.tsx
30
+ │ └── user-list.test.tsx
31
+ ├── hooks/
32
+ │ ├── use-users.ts
33
+ │ └── use-users.test.ts ← co-located
34
+ ```
35
+
36
+ ## Component Test Pattern
37
+
38
+ ```tsx
39
+ // features/users/components/user-card.test.tsx
40
+ import { render, screen } from '@testing-library/react';
41
+ import userEvent from '@testing-library/user-event';
42
+ import { UserCard } from './user-card';
43
+
44
+ const mockUser = { id: '1', name: 'João Silva', email: 'joao@example.com', role: 'user' as const };
45
+
46
+ describe('UserCard', () => {
47
+ it('renders user name and email', () => {
48
+ render(<UserCard user={mockUser} />);
49
+ expect(screen.getByText('João Silva')).toBeInTheDocument();
50
+ expect(screen.getByText('joao@example.com')).toBeInTheDocument();
51
+ });
52
+
53
+ it('calls onEdit with user id when edit button clicked', async () => {
54
+ const onEdit = vi.fn();
55
+ render(<UserCard user={mockUser} onEdit={onEdit} />);
56
+ await userEvent.click(screen.getByRole('button', { name: /edit/i }));
57
+ expect(onEdit).toHaveBeenCalledWith('1');
58
+ });
59
+ });
60
+ ```
61
+
62
+ ## Hook Test with MSW
63
+
64
+ ```ts
65
+ // features/users/hooks/use-users.test.ts
66
+ import { renderHook, waitFor } from '@testing-library/react';
67
+ import { http, HttpResponse } from 'msw';
68
+ import { server } from '@/test/msw-server';
69
+ import { QueryClientWrapper } from '@/test/helpers';
70
+ import { useUsers } from './use-users';
71
+
72
+ describe('useUsers', () => {
73
+ it('returns users from API', async () => {
74
+ server.use(
75
+ http.get('/api/proxy/users', () =>
76
+ HttpResponse.json([{ id: '1', name: 'João', email: 'j@ex.com' }])
77
+ )
78
+ );
79
+ const { result } = renderHook(() => useUsers(), { wrapper: QueryClientWrapper });
80
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
81
+ expect(result.current.data).toHaveLength(1);
82
+ });
83
+
84
+ it('returns error state when API fails', async () => {
85
+ server.use(http.get('/api/proxy/users', () => new HttpResponse(null, { status: 500 })));
86
+ const { result } = renderHook(() => useUsers(), { wrapper: QueryClientWrapper });
87
+ await waitFor(() => expect(result.current.isError).toBe(true));
88
+ });
89
+ });
90
+ ```
91
+
92
+ ## Test Helper Setup
93
+
94
+ ```tsx
95
+ // test/helpers.tsx
96
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
97
+
98
+ export function QueryClientWrapper({ children }: { children: React.ReactNode }) {
99
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
100
+ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
101
+ }
102
+ ```
103
+
104
+ ## Common Mistakes
105
+
106
+ | Wrong | Right | Why |
107
+ |-------|-------|-----|
108
+ | `fireEvent.click(button)` | `await userEvent.click(button)` | userEvent simulates real browser events |
109
+ | Mock `global.fetch` | Mock with MSW | MSW intercepts at network level |
110
+ | `expect(component).toMatchSnapshot()` | `expect(screen.getByText(...))` | Snapshots break on any change |
111
+ | Test file in `__tests__/` folder | Co-locate with source | Easier to find, deleted with the component |
112
+
113
+ ---
114
+
115
+ *MORPH-SPEC by Polymorphism Tech*