-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.ts
More file actions
249 lines (211 loc) · 7.87 KB
/
main_test.ts
File metadata and controls
249 lines (211 loc) · 7.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import {
assertEquals,
assertThrowsAsync,
import Z, { createTimeout } from "./main.ts";
// モックフェッチ関数の定義
const mockFetch = (response: any, options: { ok?: boolean; status?: number; statusText?: string } = {}) => {
const { ok = true, status = 200, statusText = "OK" } = options;
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => ({
ok,
status,
statusText,
json: async () => response,
text: async () => JSON.stringify(response),
headers: new Headers(),
redirected: false,
type: "default" as ResponseType,
url: input.toString(),
clone: function () { return this; },
body: null,
bodyUsed: false,
arrayBuffer: async () => new ArrayBuffer(0),
blob: async () => new Blob([]),
formData: async () => new FormData(),
} as Response);
};
// ヘルパー関数:オブジェクトの型チェック
const hasExpectedResponseShape = <T>(response: any): response is { data: T; response: Response } => {
return response &&
typeof response === 'object' &&
'data' in response &&
'response' in response;
};
// Zクラスのgetメソッドのテスト
Deno.test("Zクラスのgetメソッド - 基本的な動作", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const mockResponse = { title: "mock title" };
mockFetch(mockResponse);
const result = await z.get<typeof mockResponse>("/todos/1");
assertEquals(hasExpectedResponseShape(result), true);
assertEquals(result.data, mockResponse);
assertEquals(result.response?.ok, true);
});
Deno.test("Zクラスのgetメソッド - カスタムヘッダー", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const mockResponse = { title: "mock title" };
mockFetch(mockResponse);
const result = await z.get<typeof mockResponse>("/todos/1", {
headers: { "X-Custom-Header": "test" }
});
assertEquals(result.data, mockResponse);
});
// Zクラスのpostメソッドのテスト
Deno.test("Zクラスのpostメソッド - 基本的な動作", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const requestBody = { title: "mock title" };
const mockResponse = { id: 1, ...requestBody };
mockFetch(mockResponse);
const result = await z.post<typeof mockResponse>("/todos", requestBody);
assertEquals(hasExpectedResponseShape(result), true);
assertEquals(result.data, mockResponse);
});
Deno.test("Zクラスのpostメソッド - エラーハンドリング", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const mockResponse = { error: "Invalid request" };
mockFetch(mockResponse, { ok: false, status: 400, statusText: "Bad Request" });
await assertThrowsAsync(
async () => {
await z.post("/todos", { title: "" });
},
Error,
"Request failed with status 400"
);
});
// Zクラスのputメソッドのテスト
Deno.test("Zクラスのputメソッド", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const mockResponse = { title: "mock title" };
mockFetch(mockResponse);
const result = await z.put("/todos/1", { title: "updated title" });
assertEquals(result.data, mockResponse);
});
// Zクラスのdeleteメソッドのテスト
Deno.test("Zクラスのdeleteメソッド", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const mockResponse = { success: true };
mockFetch(mockResponse);
const result = await z.delete("/todos/1");
assertEquals(result.data, mockResponse);
});
// Zクラスのpatchメソッドのテスト
Deno.test("Zクラスのpatchメソッド", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const mockResponse = { title: "patched title" };
mockFetch(mockResponse);
const result = await z.patch("/todos/1", { title: "patched title" });
assertEquals(result.data, mockResponse);
});
// エラー状態のテスト
Deno.test("ネットワークエラーの処理", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
globalThis.fetch = async () => {
throw new Error("Network error");
};
await assertThrowsAsync(
async () => {
await z.get("/todos/1");
},
Error,
"Network error"
);
});
Deno.test("無効なURLの処理", async () => {
await assertThrowsAsync(
async () => {
new Z("invalid-url");
await Promise.resolve(); // 非同期コンテキストを作成
},
TypeError,
"Invalid URL"
);
});
Deno.test("レスポンスの型チェック", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const mockResponse = { title: "mock title" };
mockFetch(mockResponse);
const result = await z.get<{ title: string }>("/todos/1");
assertEquals(typeof result.data?.title, "string");
});
// AbortController のテスト
Deno.test("AbortController - リクエストをキャンセル", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const controller = new AbortController();
// フェッチをモック化して、AbortErrorを投げる
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
// シグナルがあり、既に中止されている場合はエラーを投げる
if (init?.signal && (init.signal as AbortSignal).aborted) {
const error = new Error("The operation was aborted");
error.name = "AbortError";
throw error;
}
throw new Error("Should have been aborted");
};
// リクエストの前にキャンセル
controller.abort();
await assertThrowsAsync(
async () => {
await z.get("/todos/1", { signal: controller.signal });
},
Error,
"AbortError"
);
});
Deno.test("AbortController - タイムアウト機能", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const controller = new AbortController();
// 100ms後にキャンセル
setTimeout(() => controller.abort(), 100);
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
// 長い遅延をシミュレート
await new Promise(resolve => setTimeout(resolve, 1000));
return {
ok: true,
status: 200,
json: async () => ({ data: "test" }),
} as Response;
};
await assertThrowsAsync(
async () => {
await z.get("/slow-endpoint", { signal: controller.signal });
},
Error
);
});
Deno.test("AbortController - 正常なリクエストは影響を受けない", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const controller = new AbortController();
const mockResponse = { title: "mock title" };
mockFetch(mockResponse);
// キャンセルせずにリクエスト
const result = await z.get<typeof mockResponse>("/todos/1", { signal: controller.signal });
assertEquals(result.data, mockResponse);
});
// createTimeout ヘルパー関数のテスト
Deno.test("createTimeout - タイムアウト付きAbortControllerの作成", async () => {
const controller = createTimeout(100);
// AbortControllerインスタンスであることを確認
assertEquals(controller instanceof AbortController, true);
assertEquals(controller.signal.aborted, false);
// タイムアウト後にabortされることを確認
await new Promise(resolve => setTimeout(resolve, 150));
assertEquals(controller.signal.aborted, true);
});
Deno.test("createTimeout - Zクラスとの統合", async () => {
const z = new Z("https://jsonplaceholder.typicode.com");
const controller = createTimeout(50);
globalThis.fetch = async () => {
// 長い遅延をシミュレート
await new Promise(resolve => setTimeout(resolve, 200));
return {
ok: true,
json: async () => ({ data: "test" }),
} as Response;
};
await assertThrowsAsync(
async () => {
await z.get("/slow-endpoint", { signal: controller.signal });
},
Error
);
});