@hyper-fetch/core 9.6.0 → 9.6.2
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/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
- package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
- package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
- package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
- package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
- package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
- package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
- package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
- package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
- package/__tests__/features/cache/cache.timing.spec.ts +448 -0
- package/__tests__/features/client/client.clear.spec.ts +313 -0
- package/__tests__/features/client/client.configuration.spec.ts +416 -0
- package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
- package/__tests__/features/client/client.interceptor.spec.ts +54 -45
- package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
- package/__tests__/features/client/client.user-errors.spec.ts +220 -0
- package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
- package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
- package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
- package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
- package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
- package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
- package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
- package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
- package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
- package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
- package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
- package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
- package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
- package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
- package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
- package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
- package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
- package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
- package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
- package/__tests__/features/request/request.immutability.spec.ts +259 -0
- package/__tests__/features/request/request.inference.spec.ts +269 -0
- package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
- package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
- package/__tests__/features/request/request.values.spec.ts +408 -0
- package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
- package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
- package/__tests__/utils/controlled-adapter.utils.ts +119 -0
- package/__tests__/utils/fixtures.utils.ts +193 -0
- package/dist/adapter/adapter.bindings.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/cache/cache.d.ts +12 -1
- package/dist/cache/cache.d.ts.map +1 -1
- package/dist/cache/cache.events.d.ts +20 -6
- package/dist/cache/cache.events.d.ts.map +1 -1
- package/dist/cache/cache.utils.d.ts +1 -0
- package/dist/cache/cache.utils.d.ts.map +1 -1
- package/dist/client/client.d.ts +3 -3
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.utils.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.d.ts +26 -5
- package/dist/dispatcher/dispatcher.d.ts.map +1 -1
- package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
- package/dist/index.mjs +2127 -1741
- package/dist/index.mjs.map +1 -1
- package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
- package/dist/managers/app/app.manager.d.ts +9 -0
- package/dist/managers/app/app.manager.d.ts.map +1 -1
- package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
- package/dist/managers/logger/logger.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.types.d.ts +2 -0
- package/dist/managers/request/request.manager.types.d.ts.map +1 -1
- package/dist/mocker/mocker.d.ts +1 -1
- package/dist/mocker/mocker.d.ts.map +1 -1
- package/dist/plugin/plugin.d.ts +2 -0
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/request/request.d.ts +1 -1
- package/dist/request/request.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts.map +1 -1
- package/dist/utils/emitter.utils.d.ts.map +1 -1
- package/dist/utils/error.utils.d.ts +17 -0
- package/dist/utils/error.utils.d.ts.map +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/adapter/adapter.bindings.ts +46 -18
- package/src/adapter/adapter.utils.ts +47 -7
- package/src/cache/cache.events.ts +24 -8
- package/src/cache/cache.ts +109 -21
- package/src/cache/cache.utils.ts +33 -10
- package/src/client/client.ts +99 -7
- package/src/client/client.utils.ts +10 -4
- package/src/dispatcher/dispatcher.ts +273 -133
- package/src/http-adapter/http-adapter.fetch.ts +15 -3
- package/src/managers/app/app.manager.constants.ts +12 -1
- package/src/managers/app/app.manager.ts +43 -23
- package/src/managers/app/app.manager.utils.ts +8 -4
- package/src/managers/logger/logger.manager.ts +21 -8
- package/src/managers/request/request.manager.ts +7 -1
- package/src/managers/request/request.manager.types.ts +2 -0
- package/src/mocker/mocker.ts +14 -11
- package/src/plugin/plugin.ts +6 -0
- package/src/request/request.ts +31 -22
- package/src/request/request.utils.ts +23 -15
- package/src/utils/emitter.utils.ts +9 -2
- package/src/utils/error.utils.ts +29 -0
- package/src/utils/index.ts +1 -0
|
@@ -0,0 +1,917 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vitest-environment node
|
|
3
|
+
*/
|
|
4
|
+
import { Client } from "@hyper-fetch/core";
|
|
5
|
+
import http from "http";
|
|
6
|
+
import type { AddressInfo } from "net";
|
|
7
|
+
|
|
8
|
+
import { createDeferred } from "../../utils/controlled-adapter.utils";
|
|
9
|
+
|
|
10
|
+
type Echo = {
|
|
11
|
+
method: string;
|
|
12
|
+
url: string;
|
|
13
|
+
headers: Record<string, string>;
|
|
14
|
+
body: string;
|
|
15
|
+
bodyLength: number;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Real HTTP server on a random port. Responses which must not finish on their own are held until the test (or the
|
|
20
|
+
* teardown) releases them, so nothing here depends on how fast the machine is.
|
|
21
|
+
*/
|
|
22
|
+
describe("E2E [ Fetch adapter ]", () => {
|
|
23
|
+
let server: http.Server;
|
|
24
|
+
let baseUrl = "";
|
|
25
|
+
let hits: string[] = [];
|
|
26
|
+
/** Resolved with the response of a held request when it reaches the server */
|
|
27
|
+
let received = createDeferred<http.ServerResponse>();
|
|
28
|
+
const heldResponses: http.ServerResponse[] = [];
|
|
29
|
+
|
|
30
|
+
const sendJson = (res: http.ServerResponse, status: number, data: unknown) => {
|
|
31
|
+
const body = JSON.stringify(data);
|
|
32
|
+
res.writeHead(status, {
|
|
33
|
+
"Content-Type": "application/json",
|
|
34
|
+
"Content-Length": String(Buffer.byteLength(body)),
|
|
35
|
+
"X-Custom-Response": "yes",
|
|
36
|
+
});
|
|
37
|
+
res.end(body);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const handle = (req: http.IncomingMessage, res: http.ServerResponse, body: Buffer) => {
|
|
41
|
+
const { pathname } = new URL(req.url || "/", "http://localhost");
|
|
42
|
+
hits.push(pathname);
|
|
43
|
+
|
|
44
|
+
if (pathname === "/echo") {
|
|
45
|
+
const echo: Echo = {
|
|
46
|
+
method: req.method || "",
|
|
47
|
+
url: req.url || "",
|
|
48
|
+
headers: req.headers as Record<string, string>,
|
|
49
|
+
body: body.toString("utf8"),
|
|
50
|
+
bodyLength: body.length,
|
|
51
|
+
};
|
|
52
|
+
return sendJson(res, 200, echo);
|
|
53
|
+
}
|
|
54
|
+
if (pathname.startsWith("/status/")) {
|
|
55
|
+
const status = Number(pathname.split("/")[2]);
|
|
56
|
+
if ([204, 205, 304].includes(status)) {
|
|
57
|
+
res.writeHead(status);
|
|
58
|
+
return res.end();
|
|
59
|
+
}
|
|
60
|
+
return sendJson(res, status, { status });
|
|
61
|
+
}
|
|
62
|
+
if (pathname.startsWith("/empty/")) {
|
|
63
|
+
res.writeHead(Number(pathname.split("/")[2]));
|
|
64
|
+
return res.end();
|
|
65
|
+
}
|
|
66
|
+
if (pathname === "/text") {
|
|
67
|
+
res.writeHead(200, { "Content-Type": "text/plain" });
|
|
68
|
+
return res.end("plain text response");
|
|
69
|
+
}
|
|
70
|
+
if (pathname === "/invalid-json") {
|
|
71
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
72
|
+
return res.end('{"broken": ');
|
|
73
|
+
}
|
|
74
|
+
if (pathname === "/text-error") {
|
|
75
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
76
|
+
return res.end("Something exploded");
|
|
77
|
+
}
|
|
78
|
+
if (pathname.startsWith("/redirect/")) {
|
|
79
|
+
res.writeHead(Number(pathname.split("/")[2]), { Location: "/echo" });
|
|
80
|
+
return res.end();
|
|
81
|
+
}
|
|
82
|
+
// Never answers
|
|
83
|
+
if (pathname === "/hold") {
|
|
84
|
+
heldResponses.push(res);
|
|
85
|
+
return received.resolve(res);
|
|
86
|
+
}
|
|
87
|
+
// Sends the headers and a part of the body, then stops
|
|
88
|
+
if (pathname === "/hold-body") {
|
|
89
|
+
res.writeHead(200, { "Content-Type": "application/json", "Content-Length": "100" });
|
|
90
|
+
res.write('{"partial":');
|
|
91
|
+
heldResponses.push(res);
|
|
92
|
+
return received.resolve(res);
|
|
93
|
+
}
|
|
94
|
+
if (pathname === "/chunks") {
|
|
95
|
+
res.writeHead(200, { "Content-Type": "text/plain", "Content-Length": "9" });
|
|
96
|
+
res.write("aaa");
|
|
97
|
+
// Separate writes to deliver the body in more than one piece
|
|
98
|
+
return setImmediate(() => {
|
|
99
|
+
res.write("bbb");
|
|
100
|
+
setImmediate(() => res.end("ccc"));
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
104
|
+
return res.end(JSON.stringify({ message: "Not Found" }));
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
beforeAll(async () => {
|
|
108
|
+
server = http.createServer((req, res) => {
|
|
109
|
+
const chunks: Uint8Array[] = [];
|
|
110
|
+
req.on("data", (chunk: Buffer) => chunks.push(new Uint8Array(chunk)));
|
|
111
|
+
req.on("end", () => handle(req, res, Buffer.concat(chunks)));
|
|
112
|
+
});
|
|
113
|
+
await new Promise<void>((resolve) => {
|
|
114
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
115
|
+
});
|
|
116
|
+
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
beforeEach(() => {
|
|
120
|
+
hits = [];
|
|
121
|
+
received = createDeferred<http.ServerResponse>();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
afterEach(() => {
|
|
125
|
+
heldResponses.splice(0).forEach((res) => res.destroy());
|
|
126
|
+
vi.restoreAllMocks();
|
|
127
|
+
vi.useRealTimers();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
afterAll(async () => {
|
|
131
|
+
server.closeAllConnections();
|
|
132
|
+
await new Promise((resolve) => {
|
|
133
|
+
server.close(resolve);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
const createClient = () => new Client({ url: baseUrl });
|
|
138
|
+
const createEcho = (options: { method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" } = {}) =>
|
|
139
|
+
createClient().createRequest<{ response: Echo; payload: any; queryParams: any }>()({
|
|
140
|
+
endpoint: "/echo",
|
|
141
|
+
method: "POST",
|
|
142
|
+
...options,
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe("When sending with different methods", () => {
|
|
146
|
+
it.each(["GET", "POST", "PUT", "PATCH", "DELETE"] as const)("should send the %s request", async (method) => {
|
|
147
|
+
const { data, status, success } = await createEcho({ method }).send();
|
|
148
|
+
|
|
149
|
+
expect(data?.method).toBe(method);
|
|
150
|
+
expect(status).toBe(200);
|
|
151
|
+
expect(success).toBe(true);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it("should use GET by default", async () => {
|
|
155
|
+
const request = createClient().createRequest<{ response: Echo }>()({ endpoint: "/echo" });
|
|
156
|
+
|
|
157
|
+
await expect(request.send()).resolves.toHaveProperty("data.method", "GET");
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it.each(["POST", "PUT", "PATCH", "DELETE"] as const)("should send the body with %s", async (method) => {
|
|
161
|
+
const { data } = await createEcho({ method }).send({ payload: { value: 1 } });
|
|
162
|
+
|
|
163
|
+
expect(data?.body).toBe('{"value":1}');
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("should not send the body with GET", async () => {
|
|
167
|
+
const { data, success } = await createEcho({ method: "GET" }).send({ payload: { value: 1 } });
|
|
168
|
+
|
|
169
|
+
expect(success).toBe(true);
|
|
170
|
+
expect(data?.bodyLength).toBe(0);
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
describe("When building the url", () => {
|
|
175
|
+
it("should put the params into the path", async () => {
|
|
176
|
+
const request = createClient().createRequest<{ response: { status: number } }>()({ endpoint: "/status/:code" });
|
|
177
|
+
|
|
178
|
+
const { data } = await request.send({ params: { code: 201 } });
|
|
179
|
+
|
|
180
|
+
expect(data).toEqual({ status: 201 });
|
|
181
|
+
expect(hits).toEqual(["/status/201"]);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it.each([
|
|
185
|
+
[{ page: 1, search: "john" }, "/echo?page=1&search=john"],
|
|
186
|
+
[{ search: "a b&c=d/e?f#g" }, `/echo?search=${encodeURIComponent("a b&c=d/e?f#g")}`],
|
|
187
|
+
[{ ids: [1, 2, 3] }, "/echo?ids[]=1&ids[]=2&ids[]=3"],
|
|
188
|
+
[{ empty: "", missing: null, skipped: undefined, kept: 0 }, "/echo?kept=0"],
|
|
189
|
+
[{ emoji: "żółć 🎉" }, `/echo?emoji=${encodeURIComponent("żółć 🎉")}`],
|
|
190
|
+
["raw=1&other=2", "/echo?raw=1&other=2"],
|
|
191
|
+
])("should send the query params %o", async (queryParams, url) => {
|
|
192
|
+
const { data } = await createEcho({ method: "GET" }).send({ queryParams });
|
|
193
|
+
|
|
194
|
+
expect(data?.url).toBe(url);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("should send no query string without query params", async () => {
|
|
198
|
+
const { data } = await createEcho({ method: "GET" }).send();
|
|
199
|
+
|
|
200
|
+
expect(data?.url).toBe("/echo");
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
describe("When sending headers", () => {
|
|
205
|
+
it("should describe a JSON payload with the content type", async () => {
|
|
206
|
+
const { data } = await createEcho().send({ payload: { value: 1 } });
|
|
207
|
+
|
|
208
|
+
expect(data?.headers["content-type"]).toBe("application/json");
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it("should not send the content type without a payload", async () => {
|
|
212
|
+
const { data } = await createEcho().send();
|
|
213
|
+
|
|
214
|
+
expect(data?.headers["content-type"]).toBeUndefined();
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it("should send the headers of the request", async () => {
|
|
218
|
+
const { data } = await createEcho().setHeaders({ "X-Api-Key": "key", Authorization: "Bearer token" }).send();
|
|
219
|
+
|
|
220
|
+
expect(data?.headers).toMatchObject({ "x-api-key": "key", authorization: "Bearer token" });
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it("should send the headers given as the Headers instance", async () => {
|
|
224
|
+
const headers = new Headers({ "X-Api-Key": "key" });
|
|
225
|
+
|
|
226
|
+
const { data } = await createEcho()
|
|
227
|
+
.setHeaders(headers)
|
|
228
|
+
.send({ payload: { value: 1 } });
|
|
229
|
+
|
|
230
|
+
expect(data?.headers).toMatchObject({ "x-api-key": "key", "content-type": "application/json" });
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it("should send the headers given as a list of pairs", async () => {
|
|
234
|
+
const { data } = await createEcho()
|
|
235
|
+
.setHeaders([
|
|
236
|
+
["X-Api-Key", "key"],
|
|
237
|
+
["X-Other", "other"],
|
|
238
|
+
])
|
|
239
|
+
.send();
|
|
240
|
+
|
|
241
|
+
expect(data?.headers).toMatchObject({ "x-api-key": "key", "x-other": "other" });
|
|
242
|
+
expect(data?.headers["0"]).toBeUndefined();
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it.each(["Content-Type", "content-type", "CONTENT-TYPE"])(
|
|
246
|
+
"should replace the default content type with the %s header of the request",
|
|
247
|
+
async (name) => {
|
|
248
|
+
const { data } = await createEcho()
|
|
249
|
+
.setHeaders({ [name]: "application/vnd.api+json" })
|
|
250
|
+
.send({ payload: { value: 1 } });
|
|
251
|
+
|
|
252
|
+
expect(data?.headers["content-type"]).toBe("application/vnd.api+json");
|
|
253
|
+
},
|
|
254
|
+
);
|
|
255
|
+
|
|
256
|
+
it("should not send a header with an empty value - also the default one", async () => {
|
|
257
|
+
const headers = { "Content-Type": undefined, "X-Removed": null, "X-Kept": "1" } as unknown as HeadersInit;
|
|
258
|
+
|
|
259
|
+
const { data } = await createEcho()
|
|
260
|
+
.setHeaders(headers)
|
|
261
|
+
.send({ payload: { value: 1 } });
|
|
262
|
+
|
|
263
|
+
expect(data?.headers["x-kept"]).toBe("1");
|
|
264
|
+
expect(data?.headers["x-removed"]).toBeUndefined();
|
|
265
|
+
expect(data?.headers["content-type"]).not.toBe("application/json");
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
it("should use the headers given to send over the headers of the request", async () => {
|
|
269
|
+
const { data } = await createEcho()
|
|
270
|
+
.setHeaders({ "X-Version": "1" })
|
|
271
|
+
.send({ headers: { "X-Version": "2" } });
|
|
272
|
+
|
|
273
|
+
expect(data?.headers["x-version"]).toBe("2");
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("should send the headers added by the request interceptor", async () => {
|
|
277
|
+
const client = createClient().onRequest((request) =>
|
|
278
|
+
request.setHeaders({ ...request.headers, "X-Trace": "abc" }),
|
|
279
|
+
);
|
|
280
|
+
const request = client.createRequest<{ response: Echo }>()({ endpoint: "/echo" });
|
|
281
|
+
|
|
282
|
+
const { data } = await request.setHeaders({ "X-Own": "1" }).send();
|
|
283
|
+
|
|
284
|
+
expect(data?.headers).toMatchObject({ "x-trace": "abc", "x-own": "1" });
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it("should give the response headers with lowercase names", async () => {
|
|
288
|
+
const { extra } = await createEcho().send();
|
|
289
|
+
|
|
290
|
+
expect(extra?.headers).toMatchObject({ "x-custom-response": "yes", "content-type": "application/json" });
|
|
291
|
+
});
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
describe("When sending payloads", () => {
|
|
295
|
+
it.each([
|
|
296
|
+
["an object", { name: "John", tags: ["a", "b"], nested: { ok: true } }],
|
|
297
|
+
["an array", [1, "two", { three: 3 }]],
|
|
298
|
+
["a date inside", { at: new Date(0) }],
|
|
299
|
+
["a unicode text inside", { text: "zażółć gęślą jaźń 🎉" }],
|
|
300
|
+
])("should send %s as JSON", async (_, payload) => {
|
|
301
|
+
const { data } = await createEcho().send({ payload });
|
|
302
|
+
|
|
303
|
+
const sentBody = JSON.stringify(payload);
|
|
304
|
+
|
|
305
|
+
expect(data?.body).toBe(sentBody);
|
|
306
|
+
expect(data?.headers["content-type"]).toBe("application/json");
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
it.each([
|
|
310
|
+
["zero", 0, "0"],
|
|
311
|
+
["false", false, "false"],
|
|
312
|
+
["a string", "text", '"text"'],
|
|
313
|
+
])("should send %s as a JSON value", async (_, payload, body) => {
|
|
314
|
+
const { data } = await createEcho().send({ payload });
|
|
315
|
+
|
|
316
|
+
expect(data?.body).toBe(body);
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
it.each([
|
|
320
|
+
["null", null],
|
|
321
|
+
["undefined", undefined],
|
|
322
|
+
])("should send no body for %s", async (_, payload) => {
|
|
323
|
+
const { data, success } = await createEcho().send({ payload });
|
|
324
|
+
|
|
325
|
+
expect(success).toBe(true);
|
|
326
|
+
expect(data?.bodyLength).toBe(0);
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
it("should send FormData as a multipart body", async () => {
|
|
330
|
+
const payload = new FormData();
|
|
331
|
+
payload.append("name", "John");
|
|
332
|
+
payload.append("file", new Blob(["file content"], { type: "text/plain" }), "notes.txt");
|
|
333
|
+
|
|
334
|
+
const { data } = await createEcho().send({ payload });
|
|
335
|
+
|
|
336
|
+
expect(data?.headers["content-type"]).toMatch(/^multipart\/form-data; boundary=/);
|
|
337
|
+
expect(data?.body).toContain('name="name"');
|
|
338
|
+
expect(data?.body).toContain("John");
|
|
339
|
+
expect(data?.body).toContain('filename="notes.txt"');
|
|
340
|
+
expect(data?.body).toContain("file content");
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
it("should send a Blob with its own type", async () => {
|
|
344
|
+
const payload = new Blob(["blob content"], { type: "text/csv" });
|
|
345
|
+
|
|
346
|
+
const { data } = await createEcho().send({ payload });
|
|
347
|
+
|
|
348
|
+
expect(data?.body).toBe("blob content");
|
|
349
|
+
expect(data?.headers["content-type"]).toBe("text/csv");
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
it("should send an ArrayBuffer as raw bytes", async () => {
|
|
353
|
+
const payload = new Uint8Array([1, 2, 3, 250, 251]).buffer;
|
|
354
|
+
|
|
355
|
+
const { data } = await createEcho().send({ payload });
|
|
356
|
+
|
|
357
|
+
expect(data?.bodyLength).toBe(5);
|
|
358
|
+
expect(data?.headers["content-type"]).not.toBe("application/json");
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
it("should send a typed array as raw bytes", async () => {
|
|
362
|
+
const { data } = await createEcho().send({ payload: new TextEncoder().encode("typed") });
|
|
363
|
+
|
|
364
|
+
expect(data?.body).toBe("typed");
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
it("should send URLSearchParams as a form", async () => {
|
|
368
|
+
const payload = new URLSearchParams({ name: "John Doe", role: "admin&owner" });
|
|
369
|
+
|
|
370
|
+
const { data } = await createEcho().send({ payload });
|
|
371
|
+
|
|
372
|
+
expect(data?.body).toBe("name=John+Doe&role=admin%26owner");
|
|
373
|
+
expect(data?.headers["content-type"]).toBe("application/x-www-form-urlencoded;charset=UTF-8");
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it("should send a large payload completely", async () => {
|
|
377
|
+
const payload = { text: "x".repeat(500_000) };
|
|
378
|
+
|
|
379
|
+
const { data } = await createEcho().send({ payload });
|
|
380
|
+
|
|
381
|
+
expect(data?.bodyLength).toBe(JSON.stringify(payload).length);
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
it("should send the payload returned by the payload mapper", async () => {
|
|
385
|
+
const request = createEcho().setPayloadMapper((payload: { name: string }) => `name=${payload.name}`);
|
|
386
|
+
|
|
387
|
+
const { data } = await request.send({ payload: { name: "John" } });
|
|
388
|
+
|
|
389
|
+
expect(data?.body).toBe("name=John");
|
|
390
|
+
});
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
describe("When receiving responses", () => {
|
|
394
|
+
const get = (endpoint: string, options?: object) =>
|
|
395
|
+
createClient().createRequest<{ response: any; error: any }>()({ endpoint, ...options });
|
|
396
|
+
|
|
397
|
+
it("should parse the JSON body", async () => {
|
|
398
|
+
const { data, error } = await get("/status/200").send();
|
|
399
|
+
|
|
400
|
+
expect(data).toEqual({ status: 200 });
|
|
401
|
+
expect(error).toBeNull();
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
it("should give the text body as a string", async () => {
|
|
405
|
+
const { data, success } = await get("/text").send();
|
|
406
|
+
|
|
407
|
+
expect(data).toBe("plain text response");
|
|
408
|
+
expect(success).toBe(true);
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
it.each([204, 205])("should succeed with the empty %i response", async (status) => {
|
|
412
|
+
const response = await get(`/status/${status}`).send();
|
|
413
|
+
|
|
414
|
+
expect(response.success).toBe(true);
|
|
415
|
+
expect(response.status).toBe(status);
|
|
416
|
+
expect(response.error).toBeNull();
|
|
417
|
+
expect(response.data).toBeFalsy();
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
it("should succeed with an empty 200 response", async () => {
|
|
421
|
+
const response = await get("/empty/200").send();
|
|
422
|
+
|
|
423
|
+
expect(response.success).toBe(true);
|
|
424
|
+
expect(response.error).toBeNull();
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
it("should not fail on an invalid JSON body", async () => {
|
|
428
|
+
const response = await get("/invalid-json").send();
|
|
429
|
+
|
|
430
|
+
expect(response.status).toBe(200);
|
|
431
|
+
expect(response.error).toBeNull();
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
it.each([200, 201, 202])("should treat the %i status as a success", async (status) => {
|
|
435
|
+
const response = await get(`/status/${status}`).send();
|
|
436
|
+
|
|
437
|
+
expect(response).toMatchObject({ success: true, status, error: null, data: { status } });
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
it.each([400, 401, 403, 404, 409, 422, 429, 500, 502, 503])(
|
|
441
|
+
"should treat the %i status as an error with the parsed body",
|
|
442
|
+
async (status) => {
|
|
443
|
+
const response = await get(`/status/${status}`).send();
|
|
444
|
+
|
|
445
|
+
expect(response).toMatchObject({ success: false, status, data: null, error: { status } });
|
|
446
|
+
},
|
|
447
|
+
);
|
|
448
|
+
|
|
449
|
+
it("should give the text of a non-JSON error body", async () => {
|
|
450
|
+
const response = await get("/text-error").send();
|
|
451
|
+
|
|
452
|
+
expect(response).toMatchObject({ success: false, status: 500, error: "Something exploded" });
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
it.each([400, 500])("should give the unexpected error for the %i status without a body", async (status) => {
|
|
456
|
+
const response = await get(`/empty/${status}`).send();
|
|
457
|
+
|
|
458
|
+
expect(response.success).toBe(false);
|
|
459
|
+
expect(response.status).toBe(status);
|
|
460
|
+
expect(response.error.message).toBe("Unexpected error");
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
it("should give the response timestamps in order", async () => {
|
|
464
|
+
const before = Date.now();
|
|
465
|
+
|
|
466
|
+
const { requestTimestamp, responseTimestamp } = await get("/status/200").send();
|
|
467
|
+
|
|
468
|
+
expect(requestTimestamp).toBeGreaterThanOrEqual(before);
|
|
469
|
+
expect(responseTimestamp).toBeGreaterThanOrEqual(requestTimestamp);
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
it("should give the same result with exec", async () => {
|
|
473
|
+
const response = await get("/status/404").exec({});
|
|
474
|
+
|
|
475
|
+
expect(response).toMatchObject({ success: false, status: 404, error: { status: 404 } });
|
|
476
|
+
});
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
describe("When the server redirects", () => {
|
|
480
|
+
it.each([301, 302, 303, 307, 308])("should follow the %i redirect", async (status) => {
|
|
481
|
+
const request = createClient().createRequest<{ response: Echo }>()({ endpoint: `/redirect/${status}` });
|
|
482
|
+
|
|
483
|
+
const response = await request.send();
|
|
484
|
+
|
|
485
|
+
expect(response.status).toBe(200);
|
|
486
|
+
expect(response.data?.url).toBe("/echo");
|
|
487
|
+
expect(hits).toEqual([`/redirect/${status}`, "/echo"]);
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
it("should not follow the redirect with the manual redirect option", async () => {
|
|
491
|
+
const request = createClient().createRequest<{ response: Echo }>()({
|
|
492
|
+
endpoint: "/redirect/302",
|
|
493
|
+
options: { redirect: "manual" },
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
const response = await request.send();
|
|
497
|
+
|
|
498
|
+
expect(response.status).toBe(302);
|
|
499
|
+
expect(hits).toEqual(["/redirect/302"]);
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
it("should fail on the redirect with the error redirect option", async () => {
|
|
503
|
+
const request = createClient().createRequest<{ response: Echo }>()({
|
|
504
|
+
endpoint: "/redirect/302",
|
|
505
|
+
options: { redirect: "error" },
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
const response = await request.send();
|
|
509
|
+
|
|
510
|
+
expect(response.success).toBe(false);
|
|
511
|
+
expect(response.status).toBe(0);
|
|
512
|
+
expect(hits).toEqual(["/redirect/302"]);
|
|
513
|
+
});
|
|
514
|
+
});
|
|
515
|
+
|
|
516
|
+
describe("When passing the fetch options", () => {
|
|
517
|
+
it("should pass the options of the request to fetch", async () => {
|
|
518
|
+
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
519
|
+
const options = {
|
|
520
|
+
credentials: "include",
|
|
521
|
+
mode: "cors",
|
|
522
|
+
cache: "no-store",
|
|
523
|
+
keepalive: true,
|
|
524
|
+
referrerPolicy: "no-referrer",
|
|
525
|
+
} as const;
|
|
526
|
+
|
|
527
|
+
await createEcho()
|
|
528
|
+
.setOptions(options)
|
|
529
|
+
.send({ payload: { value: 1 } });
|
|
530
|
+
const [url, init] = fetchSpy.mock.calls[0];
|
|
531
|
+
|
|
532
|
+
expect(url).toBe(`${baseUrl}/echo`);
|
|
533
|
+
expect(init).toMatchObject({ ...options, method: "POST", body: '{"value":1}' });
|
|
534
|
+
expect(init?.signal).toBeInstanceOf(AbortSignal);
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
it("should not pass its own options to fetch", async () => {
|
|
538
|
+
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
539
|
+
|
|
540
|
+
await createEcho().setOptions({ timeout: 30_000, streaming: false }).send();
|
|
541
|
+
const [, init] = fetchSpy.mock.calls[0];
|
|
542
|
+
|
|
543
|
+
expect(init).not.toHaveProperty("timeout");
|
|
544
|
+
expect(init).not.toHaveProperty("streaming");
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
it("should use the adapter defaults under the options of the request", async () => {
|
|
548
|
+
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
549
|
+
const client = createClient();
|
|
550
|
+
client.adapter.setAdapterDefaults(() => ({ credentials: "include", cache: "no-store" }));
|
|
551
|
+
const request = client.createRequest()({ endpoint: "/echo", options: { cache: "reload" } });
|
|
552
|
+
|
|
553
|
+
await request.send();
|
|
554
|
+
const [, init] = fetchSpy.mock.calls[0];
|
|
555
|
+
|
|
556
|
+
expect(init).toMatchObject({ credentials: "include", cache: "reload" });
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
it("should call fetch once per request", async () => {
|
|
560
|
+
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
561
|
+
|
|
562
|
+
await createEcho().send();
|
|
563
|
+
|
|
564
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
|
565
|
+
});
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
describe("When the request times out", () => {
|
|
569
|
+
const hold = (endpoint: string, timeout: number) =>
|
|
570
|
+
createClient().createRequest<{ response: unknown; error: Error }>()({ endpoint, options: { timeout } });
|
|
571
|
+
|
|
572
|
+
it("should give the timeout error when the server does not answer", async () => {
|
|
573
|
+
const response = await hold("/hold", 20).send();
|
|
574
|
+
|
|
575
|
+
expect(response.success).toBe(false);
|
|
576
|
+
expect(response.status).toBe(0);
|
|
577
|
+
expect(response.data).toBeNull();
|
|
578
|
+
expect(response.error?.message).toBe("Request timeout");
|
|
579
|
+
});
|
|
580
|
+
|
|
581
|
+
it("should give the timeout error when the body stops arriving", async () => {
|
|
582
|
+
// Only the timeout of the adapter is faked - it passes exactly when the headers are already here
|
|
583
|
+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
|
584
|
+
const responseStarted = createDeferred();
|
|
585
|
+
|
|
586
|
+
const sent = hold("/hold-body", 5000).send({ onResponseStart: () => responseStarted.resolve() });
|
|
587
|
+
await responseStarted.promise;
|
|
588
|
+
vi.advanceTimersByTime(5000);
|
|
589
|
+
const response = await sent;
|
|
590
|
+
|
|
591
|
+
expect(response.success).toBe(false);
|
|
592
|
+
expect(response.status).toBe(0);
|
|
593
|
+
expect(response.error?.message).toBe("Request timeout");
|
|
594
|
+
});
|
|
595
|
+
|
|
596
|
+
it("should not time out before the given time passes", async () => {
|
|
597
|
+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
|
598
|
+
const responseStarted = createDeferred();
|
|
599
|
+
const onResponse = vi.fn();
|
|
600
|
+
|
|
601
|
+
const sent = hold("/hold-body", 5000).send({ onResponseStart: () => responseStarted.resolve(), onResponse });
|
|
602
|
+
await responseStarted.promise;
|
|
603
|
+
vi.advanceTimersByTime(4999);
|
|
604
|
+
await new Promise((resolve) => {
|
|
605
|
+
setImmediate(resolve);
|
|
606
|
+
});
|
|
607
|
+
expect(onResponse).not.toHaveBeenCalled();
|
|
608
|
+
vi.advanceTimersByTime(1);
|
|
609
|
+
|
|
610
|
+
await expect(sent).resolves.toHaveProperty("error.message", "Request timeout");
|
|
611
|
+
});
|
|
612
|
+
|
|
613
|
+
it("should close the connection of a timed out request", async () => {
|
|
614
|
+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
|
615
|
+
const closed = createDeferred();
|
|
616
|
+
|
|
617
|
+
const sent = hold("/hold", 5000).send();
|
|
618
|
+
const res = await received.promise;
|
|
619
|
+
res.on("close", () => closed.resolve());
|
|
620
|
+
vi.advanceTimersByTime(5000);
|
|
621
|
+
await sent;
|
|
622
|
+
|
|
623
|
+
await expect(closed.promise).resolves.toBeUndefined();
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
it("should give the timeout error with exec", async () => {
|
|
627
|
+
const response = await hold("/hold", 20).exec({});
|
|
628
|
+
|
|
629
|
+
expect(response.error?.message).toBe("Request timeout");
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
it("should use the timeout of the adapter defaults", async () => {
|
|
633
|
+
const client = createClient();
|
|
634
|
+
client.adapter.setAdapterDefaults(() => ({ timeout: 20 }));
|
|
635
|
+
|
|
636
|
+
const response = await client.createRequest<{ error: Error }>()({ endpoint: "/hold" }).send();
|
|
637
|
+
|
|
638
|
+
expect(response.error?.message).toBe("Request timeout");
|
|
639
|
+
});
|
|
640
|
+
|
|
641
|
+
it("should not time out a request which finished in time", async () => {
|
|
642
|
+
const client = createClient();
|
|
643
|
+
const request = client.createRequest<{ response: Echo }>()({ endpoint: "/echo", options: { timeout: 60_000 } });
|
|
644
|
+
const onAbort = vi.fn();
|
|
645
|
+
client.requestManager.events.onAbort(onAbort);
|
|
646
|
+
|
|
647
|
+
const response = await request.send();
|
|
648
|
+
|
|
649
|
+
expect(response.success).toBe(true);
|
|
650
|
+
expect(onAbort).not.toHaveBeenCalled();
|
|
651
|
+
});
|
|
652
|
+
|
|
653
|
+
it("should retry a timed out request", async () => {
|
|
654
|
+
const request = createClient().createRequest<{ error: Error }>()({
|
|
655
|
+
endpoint: "/hold",
|
|
656
|
+
options: { timeout: 20 },
|
|
657
|
+
retry: 1,
|
|
658
|
+
retryTime: 0,
|
|
659
|
+
});
|
|
660
|
+
|
|
661
|
+
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
662
|
+
|
|
663
|
+
const response = await request.send();
|
|
664
|
+
|
|
665
|
+
expect(response.error?.message).toBe("Request timeout");
|
|
666
|
+
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
|
667
|
+
});
|
|
668
|
+
});
|
|
669
|
+
|
|
670
|
+
describe("When the request is aborted", () => {
|
|
671
|
+
const createHeld = (endpoint: string) => {
|
|
672
|
+
const client = createClient();
|
|
673
|
+
const request = client.createRequest<{ response: unknown; error: Error }>()({
|
|
674
|
+
endpoint,
|
|
675
|
+
options: { timeout: 60_000 },
|
|
676
|
+
});
|
|
677
|
+
return { client, request };
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
it("should not reach the server when aborted right after sending", async () => {
|
|
681
|
+
const { request } = createHeld("/hold");
|
|
682
|
+
|
|
683
|
+
const sent = request.send();
|
|
684
|
+
request.abort();
|
|
685
|
+
const response = await sent;
|
|
686
|
+
|
|
687
|
+
expect(response.error?.message).toBe("Request aborted");
|
|
688
|
+
expect(response.status).toBe(0);
|
|
689
|
+
expect(hits).toEqual([]);
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
it("should abort the request waiting for the response", async () => {
|
|
693
|
+
const { request } = createHeld("/hold");
|
|
694
|
+
|
|
695
|
+
const sent = request.send();
|
|
696
|
+
await received.promise;
|
|
697
|
+
request.abort();
|
|
698
|
+
const response = await sent;
|
|
699
|
+
|
|
700
|
+
expect(response.success).toBe(false);
|
|
701
|
+
expect(response.error?.message).toBe("Request aborted");
|
|
702
|
+
});
|
|
703
|
+
|
|
704
|
+
it("should abort the request receiving the body", async () => {
|
|
705
|
+
const { request } = createHeld("/hold-body");
|
|
706
|
+
const responseStarted = createDeferred();
|
|
707
|
+
|
|
708
|
+
const sent = request.send({ onResponseStart: () => responseStarted.resolve() });
|
|
709
|
+
await responseStarted.promise;
|
|
710
|
+
request.abort();
|
|
711
|
+
const response = await sent;
|
|
712
|
+
|
|
713
|
+
expect(response.success).toBe(false);
|
|
714
|
+
expect(response.error?.message).toBe("Request aborted");
|
|
715
|
+
});
|
|
716
|
+
|
|
717
|
+
it("should close the connection of the aborted request", async () => {
|
|
718
|
+
const { request } = createHeld("/hold");
|
|
719
|
+
const closed = createDeferred();
|
|
720
|
+
|
|
721
|
+
const sent = request.send();
|
|
722
|
+
const res = await received.promise;
|
|
723
|
+
res.on("close", () => closed.resolve());
|
|
724
|
+
request.abort();
|
|
725
|
+
await sent;
|
|
726
|
+
|
|
727
|
+
await expect(closed.promise).resolves.toBeUndefined();
|
|
728
|
+
});
|
|
729
|
+
|
|
730
|
+
it("should tell about the abort once", async () => {
|
|
731
|
+
const { client, request } = createHeld("/hold");
|
|
732
|
+
const onAbort = vi.fn();
|
|
733
|
+
client.requestManager.events.onAbort(onAbort);
|
|
734
|
+
|
|
735
|
+
const sent = request.send();
|
|
736
|
+
await received.promise;
|
|
737
|
+
request.abort();
|
|
738
|
+
request.abort();
|
|
739
|
+
await sent;
|
|
740
|
+
|
|
741
|
+
expect(onAbort).toHaveBeenCalledTimes(1);
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
it("should not change the result of a finished request", async () => {
|
|
745
|
+
const request = createEcho({ method: "GET" });
|
|
746
|
+
|
|
747
|
+
const response = await request.send();
|
|
748
|
+
request.abort();
|
|
749
|
+
|
|
750
|
+
expect(response.success).toBe(true);
|
|
751
|
+
expect(hits).toEqual(["/echo"]);
|
|
752
|
+
});
|
|
753
|
+
|
|
754
|
+
it("should abort the request made with exec", async () => {
|
|
755
|
+
const { request } = createHeld("/hold");
|
|
756
|
+
|
|
757
|
+
const sent = request.exec({});
|
|
758
|
+
await received.promise;
|
|
759
|
+
request.abort();
|
|
760
|
+
|
|
761
|
+
await expect(sent).resolves.toHaveProperty("error.message", "Request aborted");
|
|
762
|
+
});
|
|
763
|
+
|
|
764
|
+
it("should not retry the aborted request", async () => {
|
|
765
|
+
const { request } = createHeld("/hold");
|
|
766
|
+
|
|
767
|
+
const sent = request.setRetry(3).setRetryTime(0).send();
|
|
768
|
+
await received.promise;
|
|
769
|
+
request.abort();
|
|
770
|
+
await sent;
|
|
771
|
+
|
|
772
|
+
expect(hits).toEqual(["/hold"]);
|
|
773
|
+
});
|
|
774
|
+
|
|
775
|
+
it("should leave no abort controllers and running requests", async () => {
|
|
776
|
+
const { client, request } = createHeld("/hold");
|
|
777
|
+
|
|
778
|
+
const sent = request.send();
|
|
779
|
+
await received.promise;
|
|
780
|
+
request.abort();
|
|
781
|
+
await sent;
|
|
782
|
+
|
|
783
|
+
expect(client.requestManager.abortControllers.size).toBe(0);
|
|
784
|
+
expect(client.fetchDispatcher.getAllRunningRequests()).toHaveLength(0);
|
|
785
|
+
});
|
|
786
|
+
});
|
|
787
|
+
|
|
788
|
+
describe("When the network fails", () => {
|
|
789
|
+
const createUnreachable = async () => {
|
|
790
|
+
const closedServer = http.createServer();
|
|
791
|
+
await new Promise<void>((resolve) => {
|
|
792
|
+
closedServer.listen(0, "127.0.0.1", resolve);
|
|
793
|
+
});
|
|
794
|
+
const { port } = closedServer.address() as AddressInfo;
|
|
795
|
+
await new Promise((resolve) => {
|
|
796
|
+
closedServer.close(resolve);
|
|
797
|
+
});
|
|
798
|
+
return new Client({ url: `http://127.0.0.1:${port}` });
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
it("should give the error with the zero status", async () => {
|
|
802
|
+
const client = await createUnreachable();
|
|
803
|
+
|
|
804
|
+
const response = await client.createRequest<{ error: Error }>()({ endpoint: "/unreachable" }).send();
|
|
805
|
+
|
|
806
|
+
expect(response.success).toBe(false);
|
|
807
|
+
expect(response.status).toBe(0);
|
|
808
|
+
expect(response.data).toBeNull();
|
|
809
|
+
expect(response.error).toBeInstanceOf(Error);
|
|
810
|
+
expect(response.extra).toEqual({ headers: {} });
|
|
811
|
+
});
|
|
812
|
+
|
|
813
|
+
it("should retry the failed request", async () => {
|
|
814
|
+
const client = await createUnreachable();
|
|
815
|
+
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
816
|
+
|
|
817
|
+
await client.createRequest()({ endpoint: "/unreachable", retry: 2, retryTime: 0 }).send();
|
|
818
|
+
|
|
819
|
+
expect(fetchSpy).toHaveBeenCalledTimes(3);
|
|
820
|
+
});
|
|
821
|
+
|
|
822
|
+
it("should give the error for a connection dropped by the server", async () => {
|
|
823
|
+
const request = createClient().createRequest<{ error: Error }>()({
|
|
824
|
+
endpoint: "/hold-body",
|
|
825
|
+
options: { timeout: 60_000 },
|
|
826
|
+
});
|
|
827
|
+
const responseStarted = createDeferred();
|
|
828
|
+
|
|
829
|
+
const sent = request.send({ onResponseStart: () => responseStarted.resolve() });
|
|
830
|
+
await responseStarted.promise;
|
|
831
|
+
heldResponses.splice(0).forEach((res) => res.destroy());
|
|
832
|
+
const response = await sent;
|
|
833
|
+
|
|
834
|
+
expect(response.success).toBe(false);
|
|
835
|
+
expect(response.status).toBe(0);
|
|
836
|
+
});
|
|
837
|
+
});
|
|
838
|
+
|
|
839
|
+
describe("When tracking the progress", () => {
|
|
840
|
+
it("should report the download up to the full size", async () => {
|
|
841
|
+
const request = createClient().createRequest<{ response: string }>()({ endpoint: "/chunks" });
|
|
842
|
+
const progress: { loaded: number; total: number; progress: number }[] = [];
|
|
843
|
+
|
|
844
|
+
const { data } = await request.send({
|
|
845
|
+
onDownloadProgress: ({ loaded, total, progress: percent }) =>
|
|
846
|
+
progress.push({ loaded, total, progress: percent }),
|
|
847
|
+
});
|
|
848
|
+
|
|
849
|
+
expect(data).toBe("aaabbbccc");
|
|
850
|
+
expect(progress.at(-1)).toEqual({ loaded: 9, total: 9, progress: 100 });
|
|
851
|
+
// Never goes back and never reports the same state twice
|
|
852
|
+
progress.slice(1).forEach((current, index) => {
|
|
853
|
+
expect(current.loaded).toBeGreaterThanOrEqual(progress[index].loaded);
|
|
854
|
+
expect(current).not.toEqual(progress[index]);
|
|
855
|
+
});
|
|
856
|
+
});
|
|
857
|
+
|
|
858
|
+
it("should report the upload of the payload", async () => {
|
|
859
|
+
const payload = { text: "ż".repeat(100) };
|
|
860
|
+
const size = Buffer.byteLength(JSON.stringify(payload));
|
|
861
|
+
const progress: { loaded: number; total: number }[] = [];
|
|
862
|
+
|
|
863
|
+
await createEcho().send({
|
|
864
|
+
payload,
|
|
865
|
+
onUploadProgress: ({ loaded, total }) => progress.push({ loaded, total }),
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
expect(progress.at(-1)).toEqual({ loaded: size, total: size });
|
|
869
|
+
});
|
|
870
|
+
|
|
871
|
+
it("should call the lifecycle callbacks once", async () => {
|
|
872
|
+
const onRequestStart = vi.fn();
|
|
873
|
+
const onResponseStart = vi.fn();
|
|
874
|
+
const onResponse = vi.fn();
|
|
875
|
+
|
|
876
|
+
await createEcho().send({ onRequestStart, onResponseStart, onResponse });
|
|
877
|
+
|
|
878
|
+
expect(onRequestStart).toHaveBeenCalledTimes(1);
|
|
879
|
+
expect(onResponseStart).toHaveBeenCalledTimes(1);
|
|
880
|
+
expect(onResponse).toHaveBeenCalledTimes(1);
|
|
881
|
+
});
|
|
882
|
+
});
|
|
883
|
+
|
|
884
|
+
describe("When many requests are sent", () => {
|
|
885
|
+
it("should give every request its own response", async () => {
|
|
886
|
+
const request = createEcho();
|
|
887
|
+
|
|
888
|
+
const responses = await Promise.all(
|
|
889
|
+
Array.from({ length: 50 }, (_, index) => request.send({ payload: { index } })),
|
|
890
|
+
);
|
|
891
|
+
|
|
892
|
+
expect(responses.map((response) => JSON.parse(response.data!.body).index)).toEqual(
|
|
893
|
+
Array.from({ length: 50 }, (_, index) => index),
|
|
894
|
+
);
|
|
895
|
+
});
|
|
896
|
+
|
|
897
|
+
it("should send one request for the deduplicated calls", async () => {
|
|
898
|
+
const request = createClient().createRequest<{ response: Echo }>()({ endpoint: "/echo" });
|
|
899
|
+
|
|
900
|
+
const responses = await Promise.all([request.send(), request.send(), request.send()]);
|
|
901
|
+
|
|
902
|
+
expect(hits).toEqual(["/echo"]);
|
|
903
|
+
expect(responses.map((response) => response.status)).toEqual([200, 200, 200]);
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
it("should send the queued requests one after another", async () => {
|
|
907
|
+
const request = createEcho().setQueued(true);
|
|
908
|
+
const order: number[] = [];
|
|
909
|
+
|
|
910
|
+
await Promise.all(
|
|
911
|
+
[1, 2, 3, 4, 5].map((index) => request.send({ payload: { index }, onResponse: () => order.push(index) })),
|
|
912
|
+
);
|
|
913
|
+
|
|
914
|
+
expect(order).toEqual([1, 2, 3, 4, 5]);
|
|
915
|
+
});
|
|
916
|
+
});
|
|
917
|
+
});
|