@mandujs/mcp 0.9.19 → 0.9.21

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 (122) hide show
  1. package/README.md +320 -0
  2. package/package.json +1 -1
  3. package/src/activity-monitor.ts +847 -231
  4. package/src/resources/handlers.ts +244 -0
  5. package/src/resources/skills/guides.ts +1136 -0
  6. package/src/resources/skills/index.ts +12 -0
  7. package/src/resources/skills/loader.ts +218 -0
  8. package/src/resources/skills/mandu-composition/SKILL.md +91 -0
  9. package/src/resources/skills/mandu-composition/metadata.json +13 -0
  10. package/src/resources/skills/mandu-composition/rules/_sections.md +26 -0
  11. package/src/resources/skills/mandu-composition/rules/_template.md +77 -0
  12. package/src/resources/skills/mandu-composition/rules/comp-arch-avoid-boolean-props.md +146 -0
  13. package/src/resources/skills/mandu-composition/rules/comp-arch-compound-components.md +164 -0
  14. package/src/resources/skills/mandu-composition/rules/comp-island-event.md +161 -0
  15. package/src/resources/skills/mandu-composition/rules/comp-island-slot-split.md +167 -0
  16. package/src/resources/skills/mandu-composition/rules/comp-pattern-children.md +149 -0
  17. package/src/resources/skills/mandu-composition/rules/comp-state-context-interface.md +148 -0
  18. package/src/resources/skills/mandu-composition/rules/comp-state-lift-state.md +150 -0
  19. package/src/resources/skills/mandu-deployment/SKILL.md +92 -0
  20. package/src/resources/skills/mandu-deployment/_sections.md +41 -0
  21. package/src/resources/skills/mandu-deployment/_template.md +38 -0
  22. package/src/resources/skills/mandu-deployment/metadata.json +13 -0
  23. package/src/resources/skills/mandu-deployment/rules/deploy-build-bun.md +109 -0
  24. package/src/resources/skills/mandu-deployment/rules/deploy-build-output.md +115 -0
  25. package/src/resources/skills/mandu-deployment/rules/deploy-cicd-github.md +219 -0
  26. package/src/resources/skills/mandu-deployment/rules/deploy-docker-bun.md +150 -0
  27. package/src/resources/skills/mandu-deployment/rules/deploy-docker-compose.md +223 -0
  28. package/src/resources/skills/mandu-deployment/rules/deploy-platform-fly.md +152 -0
  29. package/src/resources/skills/mandu-deployment/rules/deploy-platform-render.md +179 -0
  30. package/src/resources/skills/mandu-deployment/rules/deploy-platform-supabase.md +323 -0
  31. package/src/resources/skills/mandu-deployment/rules/deploy-platform-vercel.md +140 -0
  32. package/src/resources/skills/mandu-fs-routes/SKILL.md +82 -0
  33. package/src/resources/skills/mandu-fs-routes/metadata.json +12 -0
  34. package/src/resources/skills/mandu-fs-routes/rules/_sections.md +36 -0
  35. package/src/resources/skills/mandu-fs-routes/rules/_template.md +69 -0
  36. package/src/resources/skills/mandu-fs-routes/rules/routes-api-methods.md +65 -0
  37. package/src/resources/skills/mandu-fs-routes/rules/routes-dynamic-param.md +93 -0
  38. package/src/resources/skills/mandu-fs-routes/rules/routes-naming-page.md +55 -0
  39. package/src/resources/skills/mandu-guard/SKILL.md +129 -0
  40. package/src/resources/skills/mandu-guard/metadata.json +12 -0
  41. package/src/resources/skills/mandu-guard/rules/_sections.md +36 -0
  42. package/src/resources/skills/mandu-guard/rules/_template.md +82 -0
  43. package/src/resources/skills/mandu-guard/rules/guard-config-rules.md +100 -0
  44. package/src/resources/skills/mandu-guard/rules/guard-layer-direction.md +76 -0
  45. package/src/resources/skills/mandu-guard/rules/guard-preset-mandu.md +81 -0
  46. package/src/resources/skills/mandu-guard/rules/guard-validate-import.md +80 -0
  47. package/src/resources/skills/mandu-hydration/SKILL.md +91 -0
  48. package/src/resources/skills/mandu-hydration/metadata.json +12 -0
  49. package/src/resources/skills/mandu-hydration/rules/_sections.md +31 -0
  50. package/src/resources/skills/mandu-hydration/rules/_template.md +72 -0
  51. package/src/resources/skills/mandu-hydration/rules/hydration-data-event.md +109 -0
  52. package/src/resources/skills/mandu-hydration/rules/hydration-directive-use-client.md +55 -0
  53. package/src/resources/skills/mandu-hydration/rules/hydration-island-setup.md +113 -0
  54. package/src/resources/skills/mandu-hydration/rules/hydration-priority-visible.md +68 -0
  55. package/src/resources/skills/mandu-performance/SKILL.md +85 -0
  56. package/src/resources/skills/mandu-performance/metadata.json +14 -0
  57. package/src/resources/skills/mandu-performance/rules/_sections.md +31 -0
  58. package/src/resources/skills/mandu-performance/rules/_template.md +64 -0
  59. package/src/resources/skills/mandu-performance/rules/perf-async-defer-await.md +103 -0
  60. package/src/resources/skills/mandu-performance/rules/perf-async-parallel.md +95 -0
  61. package/src/resources/skills/mandu-performance/rules/perf-bun-file.md +124 -0
  62. package/src/resources/skills/mandu-performance/rules/perf-bun-serve.md +125 -0
  63. package/src/resources/skills/mandu-performance/rules/perf-bundle-imports.md +80 -0
  64. package/src/resources/skills/mandu-performance/rules/perf-bundle-island-lazy.md +145 -0
  65. package/src/resources/skills/mandu-performance/rules/perf-cache-react.md +98 -0
  66. package/src/resources/skills/mandu-performance/rules/perf-render-transitions.md +154 -0
  67. package/src/resources/skills/mandu-security/SKILL.md +87 -0
  68. package/src/resources/skills/mandu-security/metadata.json +13 -0
  69. package/src/resources/skills/mandu-security/rules/_sections.md +31 -0
  70. package/src/resources/skills/mandu-security/rules/_template.md +74 -0
  71. package/src/resources/skills/mandu-security/rules/sec-auth-guard.md +127 -0
  72. package/src/resources/skills/mandu-security/rules/sec-env-management.md +133 -0
  73. package/src/resources/skills/mandu-security/rules/sec-input-validate.md +148 -0
  74. package/src/resources/skills/mandu-security/rules/sec-protect-csrf.md +146 -0
  75. package/src/resources/skills/mandu-security/rules/sec-protect-headers.md +138 -0
  76. package/src/resources/skills/mandu-slot/SKILL.md +85 -0
  77. package/src/resources/skills/mandu-slot/metadata.json +12 -0
  78. package/src/resources/skills/mandu-slot/rules/_sections.md +36 -0
  79. package/src/resources/skills/mandu-slot/rules/_template.md +63 -0
  80. package/src/resources/skills/mandu-slot/rules/slot-basic-structure.md +38 -0
  81. package/src/resources/skills/mandu-slot/rules/slot-ctx-response.md +56 -0
  82. package/src/resources/skills/mandu-slot/rules/slot-guard-auth.md +59 -0
  83. package/src/resources/skills/mandu-slot/rules/slot-http-methods.md +64 -0
  84. package/src/resources/skills/mandu-styling/SKILL.md +118 -0
  85. package/src/resources/skills/mandu-styling/_sections.md +36 -0
  86. package/src/resources/skills/mandu-styling/_template.md +32 -0
  87. package/src/resources/skills/mandu-styling/metadata.json +13 -0
  88. package/src/resources/skills/mandu-styling/rules/style-component-compound.md +235 -0
  89. package/src/resources/skills/mandu-styling/rules/style-component-slots.md +255 -0
  90. package/src/resources/skills/mandu-styling/rules/style-component-tokens.md +205 -0
  91. package/src/resources/skills/mandu-styling/rules/style-island-animations.md +272 -0
  92. package/src/resources/skills/mandu-styling/rules/style-island-scoping.md +167 -0
  93. package/src/resources/skills/mandu-styling/rules/style-island-variants.md +221 -0
  94. package/src/resources/skills/mandu-styling/rules/style-perf-critical.md +209 -0
  95. package/src/resources/skills/mandu-styling/rules/style-perf-purge.md +192 -0
  96. package/src/resources/skills/mandu-styling/rules/style-setup-modules.md +162 -0
  97. package/src/resources/skills/mandu-styling/rules/style-setup-panda.md +164 -0
  98. package/src/resources/skills/mandu-styling/rules/style-setup-tailwind.md +161 -0
  99. package/src/resources/skills/mandu-styling/rules/style-theme-darkmode.md +229 -0
  100. package/src/resources/skills/mandu-testing/SKILL.md +99 -0
  101. package/src/resources/skills/mandu-testing/metadata.json +13 -0
  102. package/src/resources/skills/mandu-testing/rules/_sections.md +26 -0
  103. package/src/resources/skills/mandu-testing/rules/_template.md +65 -0
  104. package/src/resources/skills/mandu-testing/rules/test-component-island.md +195 -0
  105. package/src/resources/skills/mandu-testing/rules/test-e2e-playwright.md +196 -0
  106. package/src/resources/skills/mandu-testing/rules/test-mock-fetch.md +219 -0
  107. package/src/resources/skills/mandu-testing/rules/test-slot-unit.md +192 -0
  108. package/src/resources/skills/mandu-ui/SKILL.md +117 -0
  109. package/src/resources/skills/mandu-ui/_sections.md +23 -0
  110. package/src/resources/skills/mandu-ui/_template.md +32 -0
  111. package/src/resources/skills/mandu-ui/metadata.json +13 -0
  112. package/src/resources/skills/mandu-ui/rules/ui-accessibility-aria.md +232 -0
  113. package/src/resources/skills/mandu-ui/rules/ui-accessibility-focus.md +238 -0
  114. package/src/resources/skills/mandu-ui/rules/ui-composition-patterns.md +259 -0
  115. package/src/resources/skills/mandu-ui/rules/ui-island-integration.md +258 -0
  116. package/src/resources/skills/mandu-ui/rules/ui-radix-patterns.md +213 -0
  117. package/src/resources/skills/mandu-ui/rules/ui-shadcn-setup.md +209 -0
  118. package/src/resources/skills/recipes.ts +932 -0
  119. package/src/server.ts +3 -0
  120. package/src/tools/hydration.ts +8 -8
  121. package/src/tools/index.ts +1 -0
  122. package/src/tools/seo.ts +417 -0
@@ -0,0 +1,195 @@
1
+ ---
2
+ title: Test Island Components
3
+ impact: HIGH
4
+ impactDescription: Ensures UI correctness
5
+ tags: testing, component, island, react
6
+ ---
7
+
8
+ ## Test Island Components
9
+
10
+ **Impact: HIGH (Ensures UI correctness)**
11
+
12
+ Island 컴포넌트의 렌더링과 인터랙션을 테스트하세요.
13
+
14
+ **기본 컴포넌트 테스트:**
15
+
16
+ ```typescript
17
+ // app/counter/client.test.tsx
18
+ import { describe, it, expect } from "bun:test";
19
+ import { render, screen, fireEvent } from "@testing-library/react";
20
+ import { CounterIsland } from "./client";
21
+
22
+ describe("CounterIsland", () => {
23
+ it("should render initial count", () => {
24
+ render(<CounterIsland initial={5} />);
25
+
26
+ expect(screen.getByText("Count: 5")).toBeDefined();
27
+ });
28
+
29
+ it("should increment on button click", async () => {
30
+ render(<CounterIsland initial={0} />);
31
+
32
+ const button = screen.getByRole("button", { name: /increment/i });
33
+ fireEvent.click(button);
34
+
35
+ expect(screen.getByText("Count: 1")).toBeDefined();
36
+ });
37
+
38
+ it("should decrement on button click", async () => {
39
+ render(<CounterIsland initial={10} />);
40
+
41
+ const button = screen.getByRole("button", { name: /decrement/i });
42
+ fireEvent.click(button);
43
+
44
+ expect(screen.getByText("Count: 9")).toBeDefined();
45
+ });
46
+ });
47
+ ```
48
+
49
+ ## 비동기 동작 테스트
50
+
51
+ ```typescript
52
+ // app/search/client.test.tsx
53
+ import { describe, it, expect, mock } from "bun:test";
54
+ import { render, screen, fireEvent, waitFor } from "@testing-library/react";
55
+ import { SearchIsland } from "./client";
56
+
57
+ // fetch 모킹
58
+ global.fetch = mock(() =>
59
+ Promise.resolve({
60
+ ok: true,
61
+ json: () => Promise.resolve({ results: [{ id: 1, name: "Test" }] }),
62
+ })
63
+ );
64
+
65
+ describe("SearchIsland", () => {
66
+ it("should fetch and display results", async () => {
67
+ render(<SearchIsland />);
68
+
69
+ const input = screen.getByPlaceholderText("Search...");
70
+ fireEvent.change(input, { target: { value: "test" } });
71
+
72
+ // 비동기 결과 대기
73
+ await waitFor(() => {
74
+ expect(screen.getByText("Test")).toBeDefined();
75
+ });
76
+ });
77
+
78
+ it("should show loading state", async () => {
79
+ render(<SearchIsland />);
80
+
81
+ const input = screen.getByPlaceholderText("Search...");
82
+ fireEvent.change(input, { target: { value: "test" } });
83
+
84
+ // 로딩 상태 확인
85
+ expect(screen.getByText("Loading...")).toBeDefined();
86
+ });
87
+ });
88
+ ```
89
+
90
+ ## 컴파운드 Island 테스트
91
+
92
+ ```typescript
93
+ // app/form/client.test.tsx
94
+ import { describe, it, expect } from "bun:test";
95
+ import { render, screen, fireEvent } from "@testing-library/react";
96
+ import { Form } from "./client";
97
+
98
+ describe("Form Island", () => {
99
+ it("should submit form data", async () => {
100
+ const onSubmit = mock(() => {});
101
+
102
+ render(
103
+ <Form.Provider onSubmit={onSubmit}>
104
+ <Form.Frame>
105
+ <Form.Input name="email" />
106
+ <Form.Submit>Submit</Form.Submit>
107
+ </Form.Frame>
108
+ </Form.Provider>
109
+ );
110
+
111
+ const input = screen.getByRole("textbox");
112
+ fireEvent.change(input, { target: { value: "test@example.com" } });
113
+
114
+ const button = screen.getByRole("button", { name: /submit/i });
115
+ fireEvent.click(button);
116
+
117
+ expect(onSubmit).toHaveBeenCalledWith({
118
+ email: "test@example.com",
119
+ });
120
+ });
121
+ });
122
+ ```
123
+
124
+ ## useIslandEvent 테스트
125
+
126
+ ```typescript
127
+ import { describe, it, expect } from "bun:test";
128
+ import { render, screen, fireEvent } from "@testing-library/react";
129
+ import { renderHook, act } from "@testing-library/react";
130
+ import { useIslandEvent } from "@mandujs/core/client";
131
+
132
+ describe("useIslandEvent", () => {
133
+ it("should emit and receive events", () => {
134
+ const received: number[] = [];
135
+
136
+ // 리스너 설정
137
+ const { result: listener } = renderHook(() =>
138
+ useIslandEvent<{ count: number }>("test-event", (data) => {
139
+ received.push(data.count);
140
+ })
141
+ );
142
+
143
+ // 이벤트 발송
144
+ const { result: emitter } = renderHook(() =>
145
+ useIslandEvent<{ count: number }>("test-event")
146
+ );
147
+
148
+ act(() => {
149
+ emitter.current.emit({ count: 42 });
150
+ });
151
+
152
+ expect(received).toContain(42);
153
+ });
154
+ });
155
+ ```
156
+
157
+ ## 스냅샷 테스트
158
+
159
+ ```typescript
160
+ import { describe, it, expect } from "bun:test";
161
+ import { render } from "@testing-library/react";
162
+ import { CardIsland } from "./client";
163
+
164
+ describe("CardIsland", () => {
165
+ it("should match snapshot", () => {
166
+ const { container } = render(
167
+ <CardIsland title="Test" description="Description" />
168
+ );
169
+
170
+ expect(container.innerHTML).toMatchSnapshot();
171
+ });
172
+ });
173
+ ```
174
+
175
+ ## 테스트 설정
176
+
177
+ ```typescript
178
+ // test/setup.ts
179
+ import "@testing-library/jest-dom";
180
+ import { cleanup } from "@testing-library/react";
181
+ import { afterEach } from "bun:test";
182
+
183
+ // 각 테스트 후 정리
184
+ afterEach(() => {
185
+ cleanup();
186
+ });
187
+ ```
188
+
189
+ ```json
190
+ // bunfig.toml
191
+ [test]
192
+ preload = ["./test/setup.ts"]
193
+ ```
194
+
195
+ Reference: [Testing Library React](https://testing-library.com/docs/react-testing-library/intro)
@@ -0,0 +1,196 @@
1
+ ---
2
+ title: E2E Testing with Playwright
3
+ impact: MEDIUM
4
+ impactDescription: Validates complete user flows
5
+ tags: testing, e2e, playwright, browser
6
+ ---
7
+
8
+ ## E2E Testing with Playwright
9
+
10
+ **Impact: MEDIUM (Validates complete user flows)**
11
+
12
+ Playwright를 사용하여 실제 브라우저에서 End-to-End 테스트를 실행하세요.
13
+
14
+ **Playwright 설정:**
15
+
16
+ ```bash
17
+ # 설치
18
+ bun add -d @playwright/test
19
+ bunx playwright install
20
+ ```
21
+
22
+ ```typescript
23
+ // playwright.config.ts
24
+ import { defineConfig } from "@playwright/test";
25
+
26
+ export default defineConfig({
27
+ testDir: "./tests/e2e",
28
+ fullyParallel: true,
29
+ forbidOnly: !!process.env.CI,
30
+ retries: process.env.CI ? 2 : 0,
31
+ workers: process.env.CI ? 1 : undefined,
32
+
33
+ use: {
34
+ baseURL: "http://localhost:3000",
35
+ trace: "on-first-retry",
36
+ screenshot: "only-on-failure",
37
+ },
38
+
39
+ webServer: {
40
+ command: "bun run dev",
41
+ url: "http://localhost:3000",
42
+ reuseExistingServer: !process.env.CI,
43
+ },
44
+ });
45
+ ```
46
+
47
+ **기본 E2E 테스트:**
48
+
49
+ ```typescript
50
+ // tests/e2e/home.spec.ts
51
+ import { test, expect } from "@playwright/test";
52
+
53
+ test.describe("Home Page", () => {
54
+ test("should display welcome message", async ({ page }) => {
55
+ await page.goto("/");
56
+
57
+ await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible();
58
+ });
59
+
60
+ test("should navigate to about page", async ({ page }) => {
61
+ await page.goto("/");
62
+
63
+ await page.click('a[href="/about"]');
64
+
65
+ await expect(page).toHaveURL("/about");
66
+ await expect(page.getByRole("heading", { name: "About" })).toBeVisible();
67
+ });
68
+ });
69
+ ```
70
+
71
+ ## 인증 플로우 테스트
72
+
73
+ ```typescript
74
+ // tests/e2e/auth.spec.ts
75
+ import { test, expect } from "@playwright/test";
76
+
77
+ test.describe("Authentication", () => {
78
+ test("should login successfully", async ({ page }) => {
79
+ await page.goto("/login");
80
+
81
+ // 폼 입력
82
+ await page.fill('input[name="email"]', "test@example.com");
83
+ await page.fill('input[name="password"]', "password123");
84
+
85
+ // 제출
86
+ await page.click('button[type="submit"]');
87
+
88
+ // 리다이렉트 확인
89
+ await expect(page).toHaveURL("/dashboard");
90
+ await expect(page.getByText("Welcome back")).toBeVisible();
91
+ });
92
+
93
+ test("should show error for invalid credentials", async ({ page }) => {
94
+ await page.goto("/login");
95
+
96
+ await page.fill('input[name="email"]', "wrong@example.com");
97
+ await page.fill('input[name="password"]', "wrongpassword");
98
+ await page.click('button[type="submit"]');
99
+
100
+ await expect(page.getByText("Invalid credentials")).toBeVisible();
101
+ await expect(page).toHaveURL("/login");
102
+ });
103
+
104
+ test("should logout", async ({ page }) => {
105
+ // 먼저 로그인
106
+ await page.goto("/login");
107
+ await page.fill('input[name="email"]', "test@example.com");
108
+ await page.fill('input[name="password"]', "password123");
109
+ await page.click('button[type="submit"]');
110
+
111
+ // 로그아웃
112
+ await page.click('button[aria-label="Logout"]');
113
+
114
+ await expect(page).toHaveURL("/");
115
+ await expect(page.getByText("Login")).toBeVisible();
116
+ });
117
+ });
118
+ ```
119
+
120
+ ## 인증 상태 재사용
121
+
122
+ ```typescript
123
+ // tests/e2e/auth.setup.ts
124
+ import { test as setup, expect } from "@playwright/test";
125
+
126
+ const authFile = "tests/.auth/user.json";
127
+
128
+ setup("authenticate", async ({ page }) => {
129
+ await page.goto("/login");
130
+ await page.fill('input[name="email"]', "test@example.com");
131
+ await page.fill('input[name="password"]', "password123");
132
+ await page.click('button[type="submit"]');
133
+
134
+ await expect(page).toHaveURL("/dashboard");
135
+
136
+ // 인증 상태 저장
137
+ await page.context().storageState({ path: authFile });
138
+ });
139
+ ```
140
+
141
+ ```typescript
142
+ // tests/e2e/dashboard.spec.ts
143
+ import { test, expect } from "@playwright/test";
144
+
145
+ // 저장된 인증 상태 사용
146
+ test.use({ storageState: "tests/.auth/user.json" });
147
+
148
+ test("should access dashboard when logged in", async ({ page }) => {
149
+ await page.goto("/dashboard");
150
+
151
+ // 로그인 상태로 바로 접근 가능
152
+ await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
153
+ });
154
+ ```
155
+
156
+ ## API 모킹
157
+
158
+ ```typescript
159
+ test("should display mocked data", async ({ page }) => {
160
+ // API 응답 모킹
161
+ await page.route("/api/users", async (route) => {
162
+ await route.fulfill({
163
+ status: 200,
164
+ contentType: "application/json",
165
+ body: JSON.stringify({
166
+ users: [{ id: 1, name: "Mocked User" }],
167
+ }),
168
+ });
169
+ });
170
+
171
+ await page.goto("/users");
172
+
173
+ await expect(page.getByText("Mocked User")).toBeVisible();
174
+ });
175
+ ```
176
+
177
+ ## 테스트 실행
178
+
179
+ ```bash
180
+ # 모든 테스트
181
+ bunx playwright test
182
+
183
+ # 특정 파일
184
+ bunx playwright test tests/e2e/auth.spec.ts
185
+
186
+ # UI 모드
187
+ bunx playwright test --ui
188
+
189
+ # 디버그 모드
190
+ bunx playwright test --debug
191
+
192
+ # 리포트 보기
193
+ bunx playwright show-report
194
+ ```
195
+
196
+ Reference: [Playwright Documentation](https://playwright.dev/docs/intro)
@@ -0,0 +1,219 @@
1
+ ---
2
+ title: Mock Fetch Requests in Tests
3
+ impact: MEDIUM
4
+ impactDescription: Isolates tests from external dependencies
5
+ tags: testing, mock, fetch, api
6
+ ---
7
+
8
+ ## Mock Fetch Requests in Tests
9
+
10
+ **Impact: MEDIUM (Isolates tests from external dependencies)**
11
+
12
+ 외부 API 호출을 모킹하여 테스트를 격리하고 빠르게 실행하세요.
13
+
14
+ **기본 fetch 모킹:**
15
+
16
+ ```typescript
17
+ // tests/helpers/mockFetch.ts
18
+ import { mock, beforeEach, afterEach } from "bun:test";
19
+
20
+ const originalFetch = global.fetch;
21
+
22
+ export function mockFetch(responses: Record<string, unknown>) {
23
+ global.fetch = mock((url: string, options?: RequestInit) => {
24
+ const key = `${options?.method || "GET"} ${url}`;
25
+ const response = responses[key];
26
+
27
+ if (!response) {
28
+ return Promise.reject(new Error(`No mock for: ${key}`));
29
+ }
30
+
31
+ return Promise.resolve({
32
+ ok: true,
33
+ status: 200,
34
+ json: () => Promise.resolve(response),
35
+ text: () => Promise.resolve(JSON.stringify(response)),
36
+ } as Response);
37
+ });
38
+ }
39
+
40
+ export function restoreFetch() {
41
+ global.fetch = originalFetch;
42
+ }
43
+ ```
44
+
45
+ **사용 예시:**
46
+
47
+ ```typescript
48
+ // app/users/client.test.tsx
49
+ import { describe, it, expect, beforeEach, afterEach } from "bun:test";
50
+ import { render, screen, waitFor } from "@testing-library/react";
51
+ import { mockFetch, restoreFetch } from "@/tests/helpers/mockFetch";
52
+ import { UserListIsland } from "./client";
53
+
54
+ describe("UserListIsland", () => {
55
+ beforeEach(() => {
56
+ mockFetch({
57
+ "GET /api/users": {
58
+ users: [
59
+ { id: 1, name: "Alice" },
60
+ { id: 2, name: "Bob" },
61
+ ],
62
+ },
63
+ "POST /api/users": {
64
+ user: { id: 3, name: "Charlie" },
65
+ },
66
+ });
67
+ });
68
+
69
+ afterEach(() => {
70
+ restoreFetch();
71
+ });
72
+
73
+ it("should fetch and display users", async () => {
74
+ render(<UserListIsland />);
75
+
76
+ await waitFor(() => {
77
+ expect(screen.getByText("Alice")).toBeDefined();
78
+ expect(screen.getByText("Bob")).toBeDefined();
79
+ });
80
+ });
81
+ });
82
+ ```
83
+
84
+ ## 조건부 응답 모킹
85
+
86
+ ```typescript
87
+ export function createMockFetch() {
88
+ const mocks: Array<{
89
+ match: (url: string, options?: RequestInit) => boolean;
90
+ response: () => Promise<Response>;
91
+ }> = [];
92
+
93
+ const mockFn = mock((url: string, options?: RequestInit) => {
94
+ for (const { match, response } of mocks) {
95
+ if (match(url, options)) {
96
+ return response();
97
+ }
98
+ }
99
+ return Promise.reject(new Error(`No mock for: ${url}`));
100
+ });
101
+
102
+ return {
103
+ mock: mockFn,
104
+ when: (pattern: string | RegExp) => ({
105
+ respond: (data: unknown, status = 200) => {
106
+ mocks.push({
107
+ match: (url) =>
108
+ typeof pattern === "string"
109
+ ? url.includes(pattern)
110
+ : pattern.test(url),
111
+ response: () =>
112
+ Promise.resolve({
113
+ ok: status >= 200 && status < 300,
114
+ status,
115
+ json: () => Promise.resolve(data),
116
+ } as Response),
117
+ });
118
+ },
119
+ reject: (error: Error) => {
120
+ mocks.push({
121
+ match: (url) =>
122
+ typeof pattern === "string"
123
+ ? url.includes(pattern)
124
+ : pattern.test(url),
125
+ response: () => Promise.reject(error),
126
+ });
127
+ },
128
+ }),
129
+ install: () => {
130
+ global.fetch = mockFn;
131
+ },
132
+ restore: () => {
133
+ global.fetch = originalFetch;
134
+ },
135
+ };
136
+ }
137
+ ```
138
+
139
+ **사용:**
140
+
141
+ ```typescript
142
+ const fetchMock = createMockFetch();
143
+
144
+ beforeEach(() => {
145
+ fetchMock.when("/api/users").respond({ users: [] });
146
+ fetchMock.when("/api/users/1").respond({ user: { id: 1, name: "Alice" } });
147
+ fetchMock.when("/api/error").respond({ message: "Error" }, 500);
148
+ fetchMock.install();
149
+ });
150
+
151
+ afterEach(() => {
152
+ fetchMock.restore();
153
+ });
154
+ ```
155
+
156
+ ## 에러 응답 테스트
157
+
158
+ ```typescript
159
+ it("should handle API error", async () => {
160
+ mockFetch({
161
+ "GET /api/users": { error: "Server error" },
162
+ });
163
+ // status 오버라이드
164
+ global.fetch = mock(() =>
165
+ Promise.resolve({
166
+ ok: false,
167
+ status: 500,
168
+ json: () => Promise.resolve({ error: "Server error" }),
169
+ } as Response)
170
+ );
171
+
172
+ render(<UserListIsland />);
173
+
174
+ await waitFor(() => {
175
+ expect(screen.getByText("Failed to load users")).toBeDefined();
176
+ });
177
+ });
178
+ ```
179
+
180
+ ## 네트워크 에러 테스트
181
+
182
+ ```typescript
183
+ it("should handle network error", async () => {
184
+ global.fetch = mock(() =>
185
+ Promise.reject(new Error("Network error"))
186
+ );
187
+
188
+ render(<UserListIsland />);
189
+
190
+ await waitFor(() => {
191
+ expect(screen.getByText("Network error")).toBeDefined();
192
+ });
193
+ });
194
+ ```
195
+
196
+ ## fetch 호출 검증
197
+
198
+ ```typescript
199
+ it("should call API with correct params", async () => {
200
+ const mockFn = mock(() =>
201
+ Promise.resolve({
202
+ ok: true,
203
+ json: () => Promise.resolve({ users: [] }),
204
+ } as Response)
205
+ );
206
+ global.fetch = mockFn;
207
+
208
+ render(<UserListIsland filter="active" />);
209
+
210
+ await waitFor(() => {
211
+ expect(mockFn).toHaveBeenCalledWith(
212
+ "/api/users?filter=active",
213
+ expect.objectContaining({
214
+ method: "GET",
215
+ })
216
+ );
217
+ });
218
+ });
219
+ ```