forked from rocicorp/mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch-mocker.ts
More file actions
159 lines (140 loc) · 3.92 KB
/
fetch-mocker.ts
File metadata and controls
159 lines (140 loc) · 3.92 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
import type {jest} from '@jest/globals';
import type * as vitest from 'vitest';
type Method = 'GET' | 'PUT' | 'PATCH' | 'POST' | 'DELETE';
type Handler = {
method: Method;
urlSubstring: string;
response: Response;
once?: boolean;
};
function defaultSuccessResponse<T>(result: T): Response {
return {
ok: true,
status: 200,
json: () => Promise.resolve(result),
} as unknown as Response;
}
function defaultErrorResponse(code: number, message?: string): Response {
return {
ok: false,
status: code,
statusText: message ?? '',
text: () => Promise.resolve(''),
} as unknown as Response;
}
export interface SpyOn {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
spyOn(obj: object, methodName: string): any;
}
type FetchSpy =
| vitest.MockInstance<
[input: string | Request | URL, init?: RequestInit | undefined],
Promise<Response>
>
| jest.SpiedFunction<{
(
input: URL | RequestInfo,
init?: RequestInit | undefined,
): Promise<Response>;
(
input: string | Request | URL,
init?: RequestInit | undefined,
): Promise<Response>;
}>;
export class FetchMocker {
#success: (result: unknown) => Response;
#error: (code: number, message?: string) => Response;
readonly spy: FetchSpy;
constructor(
spyOn: SpyOn,
success: (result: unknown) => Response = defaultSuccessResponse,
error: (code: number, message?: string) => Response = defaultErrorResponse,
) {
this.spy = spyOn
.spyOn(globalThis, 'fetch')
.mockImplementation(
(input: RequestInfo | URL, init: RequestInit | undefined) =>
this.#handle(input, init),
);
this.#success = success;
this.#error = error;
}
readonly handlers: Handler[] = [];
#defaultResponse: Response = {
ok: false,
status: 404,
text: () => Promise.resolve('not found'),
} as unknown as Response;
#handle(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
for (let i = 0; i < this.handlers.length; i++) {
const handler = this.handlers[i];
if (
handler.method === (init?.method ?? 'GET') &&
input.toString().includes(handler.urlSubstring)
) {
if (handler.once) {
this.handlers.splice(i, 1);
}
return Promise.resolve(handler.response);
}
}
return Promise.resolve(this.#defaultResponse);
}
default<T extends Record<string, unknown>>(result: T): this;
default(errorCode: number, message?: string): this;
default(
errorCodeOrResult: number | Record<string, unknown>,
message?: string,
): this {
this.#defaultResponse =
typeof errorCodeOrResult === 'number'
? this.#error(errorCodeOrResult, message)
: this.#success(errorCodeOrResult);
return this;
}
result<T>(method: Method, urlSubstring: string, json: T): this {
this.handlers.push({
method,
urlSubstring,
response: this.#success(json),
});
return this;
}
error(
method: Method,
urlSubstring: string,
code: number,
message?: string,
): this {
this.handlers.push({
method,
urlSubstring,
response: this.#error(code, message),
});
return this;
}
/**
* Configures the last specified handler (via result() or error()) to only be applied once.
*/
once(): this {
this.handlers[this.handlers.length - 1].once = true;
return this;
}
requests(): [method: string, url: string][] {
return this.spy.mock.calls.map(([input, init]) => [
init?.method ?? 'GET',
input.toString(),
]);
}
bodys(): (BodyInit | null | undefined)[] {
return this.spy.mock.calls.map(([_, init]) => init?.body);
}
headers(): (HeadersInit | undefined)[] {
return this.spy.mock.calls.map(([_, init]) => init?.headers);
}
jsonPayloads(): unknown[] {
return this.spy.mock.calls.map(([_, init]) =>
JSON.parse(String(init?.body)),
);
}
}