@baukit/api-runtime 0.7.2 → 0.7.3
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/package.json +2 -1
- package/src/backoff.test.ts +32 -0
- package/src/backoff.ts +22 -0
- package/src/erasure.test.ts +333 -0
- package/src/erasure.ts +229 -0
- package/src/idempotency.test.ts +423 -0
- package/src/idempotency.ts +258 -0
- package/src/index.test.ts +453 -0
- package/src/index.ts +727 -0
- package/src/unverified-display-identity.test.ts +72 -0
- package/src/unverified-display-identity.ts +96 -0
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
ApiError,
|
|
5
|
+
HttpError,
|
|
6
|
+
IDEMPOTENCY_KEY_HEADER,
|
|
7
|
+
MockFetch,
|
|
8
|
+
NetworkError,
|
|
9
|
+
REQUEST_ID_HEADER,
|
|
10
|
+
createApiFetch,
|
|
11
|
+
createApiRuntime,
|
|
12
|
+
isApiError,
|
|
13
|
+
isHttpError,
|
|
14
|
+
isNetworkError,
|
|
15
|
+
normalizeResponseError,
|
|
16
|
+
parseApiErrorEnvelope,
|
|
17
|
+
resolveApiEnvironment,
|
|
18
|
+
} from './index.js';
|
|
19
|
+
|
|
20
|
+
const baseOptions = { baseUrl: 'https://api.example.test/v1', environment: 'test' } as const;
|
|
21
|
+
const rustEnvelopeSample = {
|
|
22
|
+
error: {
|
|
23
|
+
code: 'validation_failed',
|
|
24
|
+
message: 'The request is invalid',
|
|
25
|
+
requestId: 'req-123',
|
|
26
|
+
details: {},
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
describe('configuration', () => {
|
|
31
|
+
it('resolves a caller-provided environment map without ambient environment access', () => {
|
|
32
|
+
expect(
|
|
33
|
+
resolveApiEnvironment('staging', {
|
|
34
|
+
production: 'https://api.example.test',
|
|
35
|
+
staging: 'https://staging.example.test/',
|
|
36
|
+
}),
|
|
37
|
+
).toEqual({ baseUrl: 'https://staging.example.test', environment: 'staging' });
|
|
38
|
+
expect(() => resolveApiEnvironment('preview', {})).toThrow('Unknown API environment: preview');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('resolves standalone relative paths against the configured base URL', async () => {
|
|
42
|
+
const mock = new MockFetch().enqueueJson({ ok: true });
|
|
43
|
+
const runtime = createApiRuntime({ ...baseOptions, fetch: mock.fetch, retry: false });
|
|
44
|
+
await runtime.fetch('widgets');
|
|
45
|
+
mock.assertRequest(0, { url: 'https://api.example.test/v1/widgets' });
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('Baukit error normalization', () => {
|
|
50
|
+
it('parses the serialized Rust envelope shape', () => {
|
|
51
|
+
const error = parseApiErrorEnvelope(rustEnvelopeSample, 400);
|
|
52
|
+
expect(error).toBeInstanceOf(ApiError);
|
|
53
|
+
expect(error).toMatchObject({
|
|
54
|
+
code: 'validation_failed',
|
|
55
|
+
details: {},
|
|
56
|
+
kind: 'api',
|
|
57
|
+
message: 'The request is invalid',
|
|
58
|
+
requestId: 'req-123',
|
|
59
|
+
status: 400,
|
|
60
|
+
});
|
|
61
|
+
expect(isApiError(error, 'validation_failed')).toBe(true);
|
|
62
|
+
expect(isApiError(error, 'not_found')).toBe(false);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('rejects lookalike and malformed envelopes', () => {
|
|
66
|
+
expect(parseApiErrorEnvelope({ error: { ...rustEnvelopeSample.error } }, 400)).toBeInstanceOf(
|
|
67
|
+
ApiError,
|
|
68
|
+
);
|
|
69
|
+
expect(
|
|
70
|
+
parseApiErrorEnvelope({ error: { ...rustEnvelopeSample.error, request_id: 'wrong' } }, 400),
|
|
71
|
+
).toMatchObject({ requestId: 'req-123' });
|
|
72
|
+
expect(
|
|
73
|
+
parseApiErrorEnvelope(
|
|
74
|
+
{ error: { code: 'bad', message: 'Bad', request_id: 'snake', details: {} } },
|
|
75
|
+
400,
|
|
76
|
+
),
|
|
77
|
+
).toBeNull();
|
|
78
|
+
expect(
|
|
79
|
+
parseApiErrorEnvelope({ error: { ...rustEnvelopeSample.error, details: [] } }, 400),
|
|
80
|
+
).toBeNull();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('normalizes non-envelope JSON and non-JSON responses as HttpError', async () => {
|
|
84
|
+
const jsonError = await normalizeResponseError(
|
|
85
|
+
new Response(JSON.stringify({ message: 'upstream failed' }), {
|
|
86
|
+
status: 500,
|
|
87
|
+
headers: { [REQUEST_ID_HEADER]: 'header-request' },
|
|
88
|
+
}),
|
|
89
|
+
);
|
|
90
|
+
expect(jsonError).toBeInstanceOf(HttpError);
|
|
91
|
+
expect(jsonError).toMatchObject({
|
|
92
|
+
body: { message: 'upstream failed' },
|
|
93
|
+
kind: 'http',
|
|
94
|
+
requestId: 'header-request',
|
|
95
|
+
status: 500,
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const textError = await normalizeResponseError(new Response('not json', { status: 502 }));
|
|
99
|
+
expect(isHttpError(textError)).toBe(true);
|
|
100
|
+
expect(textError).toMatchObject({ body: 'not json' });
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('normalizes transport failures without exposing raw fetch errors', async () => {
|
|
104
|
+
const raw = new TypeError('Failed to fetch');
|
|
105
|
+
const mock = new MockFetch().enqueue(raw);
|
|
106
|
+
const apiFetch = createApiFetch({ ...baseOptions, fetch: mock.fetch, retry: false });
|
|
107
|
+
|
|
108
|
+
const caught = await apiFetch('/widgets').catch((error: unknown) => error);
|
|
109
|
+
expect(caught).toBeInstanceOf(NetworkError);
|
|
110
|
+
expect(isNetworkError(caught)).toBe(true);
|
|
111
|
+
expect(caught).toMatchObject({ aborted: false, cause: raw, kind: 'network' });
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
describe('request decoration', () => {
|
|
116
|
+
it('injects a fresh bearer token and request ID per request', async () => {
|
|
117
|
+
const mock = new MockFetch().enqueueJson({}).enqueueJson({});
|
|
118
|
+
const tokenProvider = vi
|
|
119
|
+
.fn()
|
|
120
|
+
.mockResolvedValueOnce('first-token')
|
|
121
|
+
.mockResolvedValueOnce('second-token');
|
|
122
|
+
const apiFetch = createApiFetch({
|
|
123
|
+
...baseOptions,
|
|
124
|
+
fetch: mock.fetch,
|
|
125
|
+
retry: false,
|
|
126
|
+
tokenProvider,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
await apiFetch('/one');
|
|
130
|
+
await apiFetch('/two');
|
|
131
|
+
|
|
132
|
+
expect(tokenProvider).toHaveBeenCalledTimes(2);
|
|
133
|
+
expect(mock.request(0).headers.get('authorization')).toBe('Bearer first-token');
|
|
134
|
+
expect(mock.request(1).headers.get('authorization')).toBe('Bearer second-token');
|
|
135
|
+
const firstId = mock.request(0).headers.get(REQUEST_ID_HEADER);
|
|
136
|
+
const secondId = mock.request(1).headers.get(REQUEST_ID_HEADER);
|
|
137
|
+
expect(firstId).toMatch(
|
|
138
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
|
|
139
|
+
);
|
|
140
|
+
expect(secondId).not.toBe(firstId);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('does not inject authorization for a null token', async () => {
|
|
144
|
+
const mock = new MockFetch().enqueueJson({});
|
|
145
|
+
const apiFetch = createApiFetch({
|
|
146
|
+
...baseOptions,
|
|
147
|
+
fetch: mock.fetch,
|
|
148
|
+
retry: false,
|
|
149
|
+
tokenProvider: () => Promise.resolve(null),
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
await apiFetch('/anonymous');
|
|
153
|
+
expect(mock.request(0).headers.has('authorization')).toBe(false);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('injects traceparent only when its optional provider is configured', async () => {
|
|
157
|
+
const mock = new MockFetch().enqueueJson({}).enqueueJson({});
|
|
158
|
+
await createApiFetch({ ...baseOptions, fetch: mock.fetch, retry: false })('/without-trace');
|
|
159
|
+
await createApiFetch({
|
|
160
|
+
...baseOptions,
|
|
161
|
+
fetch: mock.fetch,
|
|
162
|
+
retry: false,
|
|
163
|
+
traceparentProvider: () => '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
|
|
164
|
+
})('/with-trace');
|
|
165
|
+
|
|
166
|
+
expect(mock.request(0).headers.has('traceparent')).toBe(false);
|
|
167
|
+
expect(mock.request(1).headers.get('traceparent')).toBe(
|
|
168
|
+
'00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
|
|
169
|
+
);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('fires the 401 hook with the normalized error before rejecting', async () => {
|
|
173
|
+
const mock = new MockFetch().enqueueJson(rustEnvelopeSample, { status: 401 });
|
|
174
|
+
const onUnauthorized = vi.fn();
|
|
175
|
+
const apiFetch = createApiFetch({
|
|
176
|
+
...baseOptions,
|
|
177
|
+
fetch: mock.fetch,
|
|
178
|
+
onUnauthorized,
|
|
179
|
+
retry: false,
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
await expect(apiFetch('/private')).rejects.toMatchObject({
|
|
183
|
+
code: 'validation_failed',
|
|
184
|
+
status: 401,
|
|
185
|
+
});
|
|
186
|
+
expect(onUnauthorized).toHaveBeenCalledOnce();
|
|
187
|
+
expect(onUnauthorized).toHaveBeenCalledWith(
|
|
188
|
+
expect.objectContaining({ canRetry: true, error: expect.any(ApiError) as ApiError }),
|
|
189
|
+
);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it('reacquires credentials and replays one cloneable request after explicit consent', async () => {
|
|
193
|
+
const mock = new MockFetch()
|
|
194
|
+
.enqueueJson(rustEnvelopeSample, { status: 401 })
|
|
195
|
+
.enqueueJson({ ok: true });
|
|
196
|
+
const tokenProvider = vi
|
|
197
|
+
.fn()
|
|
198
|
+
.mockResolvedValueOnce('expired-token')
|
|
199
|
+
.mockResolvedValue('fresh-token');
|
|
200
|
+
const onUnauthorized = vi.fn().mockResolvedValue('retry-once');
|
|
201
|
+
const apiFetch = createApiFetch({
|
|
202
|
+
...baseOptions,
|
|
203
|
+
fetch: mock.fetch,
|
|
204
|
+
onUnauthorized,
|
|
205
|
+
retry: false,
|
|
206
|
+
tokenProvider,
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
await expect(apiFetch('/private')).resolves.toHaveProperty('status', 200);
|
|
210
|
+
expect(mock.requests).toHaveLength(2);
|
|
211
|
+
expect(mock.request(0).headers.get('authorization')).toBe('Bearer expired-token');
|
|
212
|
+
expect(mock.request(1).headers.get('authorization')).toBe('Bearer fresh-token');
|
|
213
|
+
expect(tokenProvider).toHaveBeenCalledTimes(2);
|
|
214
|
+
expect(onUnauthorized).toHaveBeenCalledOnce();
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it('stops after the replay returns a second 401', async () => {
|
|
218
|
+
const mock = new MockFetch()
|
|
219
|
+
.enqueueJson(rustEnvelopeSample, { status: 401 })
|
|
220
|
+
.enqueueJson(rustEnvelopeSample, { status: 401 });
|
|
221
|
+
const onUnauthorized = vi.fn().mockReturnValue('retry-once');
|
|
222
|
+
const apiFetch = createApiFetch({
|
|
223
|
+
...baseOptions,
|
|
224
|
+
fetch: mock.fetch,
|
|
225
|
+
onUnauthorized,
|
|
226
|
+
retry: false,
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
await expect(apiFetch('/private')).rejects.toMatchObject({ status: 401 });
|
|
230
|
+
expect(mock.requests).toHaveLength(2);
|
|
231
|
+
expect(onUnauthorized).toHaveBeenCalledOnce();
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it('notifies the product when the one credential replay is exhausted', async () => {
|
|
235
|
+
const mock = new MockFetch()
|
|
236
|
+
.enqueueJson(rustEnvelopeSample, { status: 401 })
|
|
237
|
+
.enqueueJson(rustEnvelopeSample, { status: 401 });
|
|
238
|
+
const onUnauthorizedExhausted = vi.fn();
|
|
239
|
+
const apiFetch = createApiFetch({
|
|
240
|
+
...baseOptions,
|
|
241
|
+
fetch: mock.fetch,
|
|
242
|
+
onUnauthorized: () => 'retry-once',
|
|
243
|
+
onUnauthorizedExhausted,
|
|
244
|
+
retry: false,
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
await expect(apiFetch('/private')).rejects.toMatchObject({ status: 401 });
|
|
248
|
+
expect(onUnauthorizedExhausted).toHaveBeenCalledOnce();
|
|
249
|
+
expect(onUnauthorizedExhausted).toHaveBeenCalledWith(
|
|
250
|
+
expect.objectContaining({ canRetry: false, error: expect.any(ApiError) as ApiError }),
|
|
251
|
+
);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it('honors abort while unauthorized recovery is running', async () => {
|
|
255
|
+
const controller = new AbortController();
|
|
256
|
+
const mock = new MockFetch()
|
|
257
|
+
.enqueueJson(rustEnvelopeSample, { status: 401 })
|
|
258
|
+
.enqueueJson({ ok: true });
|
|
259
|
+
const apiFetch = createApiFetch({
|
|
260
|
+
...baseOptions,
|
|
261
|
+
fetch: mock.fetch,
|
|
262
|
+
onUnauthorized: () => {
|
|
263
|
+
controller.abort('stop recovery');
|
|
264
|
+
return 'retry-once';
|
|
265
|
+
},
|
|
266
|
+
retry: false,
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
const caught = await apiFetch('/private', { signal: controller.signal }).catch(
|
|
270
|
+
(error: unknown) => error,
|
|
271
|
+
);
|
|
272
|
+
expect(caught).toBeInstanceOf(NetworkError);
|
|
273
|
+
expect(caught).toMatchObject({ aborted: true });
|
|
274
|
+
expect(mock.requests).toHaveLength(1);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
it('reports a non-cloneable request and preserves the original 401', async () => {
|
|
278
|
+
class NonCloneableRequest extends Request {
|
|
279
|
+
public override clone(): Request {
|
|
280
|
+
throw new TypeError('body cannot be cloned');
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const mock = new MockFetch().enqueueJson(rustEnvelopeSample, { status: 401 });
|
|
285
|
+
const onUnauthorized = vi.fn().mockReturnValue('retry-once');
|
|
286
|
+
const apiFetch = createApiFetch({
|
|
287
|
+
...baseOptions,
|
|
288
|
+
fetch: mock.fetch,
|
|
289
|
+
onUnauthorized,
|
|
290
|
+
requestConstructor: NonCloneableRequest,
|
|
291
|
+
retry: false,
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
await expect(apiFetch('/private', { body: 'one-shot', method: 'POST' })).rejects.toMatchObject({
|
|
295
|
+
status: 401,
|
|
296
|
+
});
|
|
297
|
+
expect(mock.requests).toHaveLength(1);
|
|
298
|
+
expect(onUnauthorized).toHaveBeenCalledWith(expect.objectContaining({ canRetry: false }));
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
describe('retry policy', () => {
|
|
303
|
+
it('retries GET network errors and 502/503/504 using bounded exponential full jitter', async () => {
|
|
304
|
+
const delays: number[] = [];
|
|
305
|
+
const mock = new MockFetch()
|
|
306
|
+
.enqueue(new TypeError('offline'))
|
|
307
|
+
.enqueue(new Response(null, { status: 503 }))
|
|
308
|
+
.enqueueJson({ ok: true });
|
|
309
|
+
const apiFetch = createApiFetch({
|
|
310
|
+
...baseOptions,
|
|
311
|
+
fetch: mock.fetch,
|
|
312
|
+
retry: {
|
|
313
|
+
baseDelayMs: 100,
|
|
314
|
+
maxDelayMs: 150,
|
|
315
|
+
maxRetries: 2,
|
|
316
|
+
random: () => 1,
|
|
317
|
+
sleep: (delay) => {
|
|
318
|
+
delays.push(delay);
|
|
319
|
+
return Promise.resolve();
|
|
320
|
+
},
|
|
321
|
+
},
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
await expect(apiFetch('/eventually')).resolves.toHaveProperty('status', 200);
|
|
325
|
+
expect(mock.requests).toHaveLength(3);
|
|
326
|
+
expect(delays).toEqual([100, 150]);
|
|
327
|
+
expect(
|
|
328
|
+
new Set(mock.requests.map((request) => request.headers.get(REQUEST_ID_HEADER))).size,
|
|
329
|
+
).toBe(1);
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
it.each(['POST', 'PATCH'] as const)(
|
|
333
|
+
'never retries %s without an idempotency key',
|
|
334
|
+
async (method) => {
|
|
335
|
+
const mock = new MockFetch().enqueue(new TypeError('offline')).enqueueJson({ ok: true });
|
|
336
|
+
const apiFetch = createApiFetch({
|
|
337
|
+
...baseOptions,
|
|
338
|
+
fetch: mock.fetch,
|
|
339
|
+
retry: { baseDelayMs: 0, methods: ['GET', method] },
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
await expect(apiFetch('/write', { method })).rejects.toBeInstanceOf(NetworkError);
|
|
343
|
+
expect(mock.requests).toHaveLength(1);
|
|
344
|
+
},
|
|
345
|
+
);
|
|
346
|
+
|
|
347
|
+
it.each(['POST', 'PATCH'] as const)(
|
|
348
|
+
'retries opted-in %s with the same idempotency key',
|
|
349
|
+
async (method) => {
|
|
350
|
+
const mock = new MockFetch()
|
|
351
|
+
.enqueue(new TypeError('offline'))
|
|
352
|
+
.enqueue(new Response(null, { status: 503 }))
|
|
353
|
+
.enqueueJson({ ok: true }, { status: 201 });
|
|
354
|
+
const apiFetch = createApiFetch({
|
|
355
|
+
...baseOptions,
|
|
356
|
+
fetch: mock.fetch,
|
|
357
|
+
retry: { baseDelayMs: 0, methods: [method] },
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
await expect(
|
|
361
|
+
apiFetch('/write', {
|
|
362
|
+
body: '{"title":"standup"}',
|
|
363
|
+
headers: { [IDEMPOTENCY_KEY_HEADER]: 'key-1' },
|
|
364
|
+
method,
|
|
365
|
+
}),
|
|
366
|
+
).resolves.toHaveProperty('status', 201);
|
|
367
|
+
expect(mock.requests.map((request) => request.headers.get(IDEMPOTENCY_KEY_HEADER))).toEqual([
|
|
368
|
+
'key-1',
|
|
369
|
+
'key-1',
|
|
370
|
+
'key-1',
|
|
371
|
+
]);
|
|
372
|
+
await expect(mock.requests[2]?.text()).resolves.toBe('{"title":"standup"}');
|
|
373
|
+
},
|
|
374
|
+
);
|
|
375
|
+
|
|
376
|
+
it('does not retry a keyed POST unless POST is opted in', async () => {
|
|
377
|
+
const mock = new MockFetch().enqueue(new Response(null, { status: 503 })).enqueueJson({});
|
|
378
|
+
const apiFetch = createApiFetch({ ...baseOptions, fetch: mock.fetch });
|
|
379
|
+
|
|
380
|
+
await expect(
|
|
381
|
+
apiFetch('/write', { headers: { [IDEMPOTENCY_KEY_HEADER]: 'key-1' }, method: 'POST' }),
|
|
382
|
+
).rejects.toMatchObject({ status: 503 });
|
|
383
|
+
expect(mock.requests).toHaveLength(1);
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
it('defaults to GET/HEAD and permits explicit idempotent-method opt-in', async () => {
|
|
387
|
+
const defaultMock = new MockFetch()
|
|
388
|
+
.enqueue(new Response(null, { status: 503 }))
|
|
389
|
+
.enqueueJson({});
|
|
390
|
+
await expect(
|
|
391
|
+
createApiFetch({ ...baseOptions, fetch: defaultMock.fetch })('/put', { method: 'PUT' }),
|
|
392
|
+
).rejects.toMatchObject({ status: 503 });
|
|
393
|
+
expect(defaultMock.requests).toHaveLength(1);
|
|
394
|
+
|
|
395
|
+
const optInMock = new MockFetch().enqueue(new Response(null, { status: 504 })).enqueueJson({});
|
|
396
|
+
await expect(
|
|
397
|
+
createApiFetch({
|
|
398
|
+
...baseOptions,
|
|
399
|
+
fetch: optInMock.fetch,
|
|
400
|
+
retry: { baseDelayMs: 0, methods: ['PUT'] },
|
|
401
|
+
})('/put', { method: 'PUT' }),
|
|
402
|
+
).resolves.toHaveProperty('status', 200);
|
|
403
|
+
expect(optInMock.requests).toHaveLength(2);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
it('never retries 4xx responses', async () => {
|
|
407
|
+
const mock = new MockFetch().enqueueJson(rustEnvelopeSample, { status: 429 }).enqueueJson({});
|
|
408
|
+
const apiFetch = createApiFetch({ ...baseOptions, fetch: mock.fetch });
|
|
409
|
+
|
|
410
|
+
await expect(apiFetch('/limited')).rejects.toBeInstanceOf(ApiError);
|
|
411
|
+
expect(mock.requests).toHaveLength(1);
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
it('aborts during backoff and does not make another attempt', async () => {
|
|
415
|
+
const controller = new AbortController();
|
|
416
|
+
const mock = new MockFetch().enqueue(new Response(null, { status: 503 })).enqueueJson({});
|
|
417
|
+
const apiFetch = createApiFetch({
|
|
418
|
+
...baseOptions,
|
|
419
|
+
fetch: mock.fetch,
|
|
420
|
+
retry: {
|
|
421
|
+
sleep: async (_delay, signal) => {
|
|
422
|
+
await Promise.resolve();
|
|
423
|
+
controller.abort('stop');
|
|
424
|
+
signal?.throwIfAborted();
|
|
425
|
+
},
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
const caught = await apiFetch('/slow', { signal: controller.signal }).catch(
|
|
430
|
+
(error: unknown) => error,
|
|
431
|
+
);
|
|
432
|
+
expect(caught).toBeInstanceOf(NetworkError);
|
|
433
|
+
expect(caught).toMatchObject({ aborted: true });
|
|
434
|
+
expect(mock.requests).toHaveLength(1);
|
|
435
|
+
});
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
describe('MockFetch assertions', () => {
|
|
439
|
+
it('queues responses and asserts recorded requests', async () => {
|
|
440
|
+
const mock = new MockFetch().enqueueJson({ ok: true });
|
|
441
|
+
await mock.fetch('https://api.example.test/ping', { headers: { 'x-test': 'yes' } });
|
|
442
|
+
expect(() => {
|
|
443
|
+
mock.assertRequest(0, {
|
|
444
|
+
headers: { 'x-test': 'yes' },
|
|
445
|
+
method: 'GET',
|
|
446
|
+
url: 'https://api.example.test/ping',
|
|
447
|
+
});
|
|
448
|
+
}).not.toThrow();
|
|
449
|
+
expect(() => {
|
|
450
|
+
mock.assertQueueEmpty();
|
|
451
|
+
}).not.toThrow();
|
|
452
|
+
});
|
|
453
|
+
});
|