@remit/web-client 0.0.53 → 0.0.55

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.
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Fetch seam for the tests. The generated SDK talks to the network through
3
+ * `globalThis.fetch`, so intercepting it — rather than the client module —
4
+ * exercises the real request the app builds: method, path, and JSON body.
5
+ */
6
+
7
+ export interface HttpCall {
8
+ method: string;
9
+ url: string;
10
+ path: string;
11
+ body: Record<string, unknown> | undefined;
12
+ }
13
+
14
+ export interface HttpMock {
15
+ calls: HttpCall[];
16
+ /** Calls whose path ends with `suffix`, in order. */
17
+ to: (suffix: string) => HttpCall[];
18
+ restore: () => void;
19
+ }
20
+
21
+ type Responder = (call: HttpCall) => unknown;
22
+
23
+ /**
24
+ * Answer every request with `responder`'s return value as JSON. Throwing from
25
+ * the responder, or returning a `Response`, is how a test drives a failure.
26
+ */
27
+ export const mockFetch = (responder: Responder = () => ({})): HttpMock => {
28
+ const original = globalThis.fetch;
29
+ const calls: HttpCall[] = [];
30
+
31
+ globalThis.fetch = (async (
32
+ input: RequestInfo | URL,
33
+ init?: RequestInit,
34
+ ): Promise<Response> => {
35
+ const request = input instanceof Request ? input : undefined;
36
+ const url = request ? request.url : String(input);
37
+ const rawBody = request ? await request.clone().text() : undefined;
38
+ const call: HttpCall = {
39
+ method: (request?.method ?? init?.method ?? "GET").toUpperCase(),
40
+ url,
41
+ path: new URL(url, "http://localhost").pathname,
42
+ body: rawBody ? JSON.parse(rawBody) : undefined,
43
+ };
44
+ calls.push(call);
45
+
46
+ const result = responder(call);
47
+ if (result instanceof Response) return result;
48
+ return new Response(JSON.stringify(result ?? {}), {
49
+ status: 200,
50
+ headers: { "content-type": "application/json" },
51
+ });
52
+ }) as typeof globalThis.fetch;
53
+
54
+ return {
55
+ calls,
56
+ to: (suffix) => calls.filter((call) => call.path.endsWith(suffix)),
57
+ restore: () => {
58
+ globalThis.fetch = original;
59
+ },
60
+ };
61
+ };
62
+
63
+ /**
64
+ * A failed request. The status travels in the body as well as on the response:
65
+ * the generated client throws the parsed body, and the app's error classifier
66
+ * reads the status off it.
67
+ */
68
+ export const httpError = (status: number, message = "boom"): Response =>
69
+ new Response(JSON.stringify({ status, message }), {
70
+ status,
71
+ headers: { "content-type": "application/json" },
72
+ });