-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.test.ts
More file actions
660 lines (591 loc) · 21.5 KB
/
Copy pathclient.test.ts
File metadata and controls
660 lines (591 loc) · 21.5 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
import { describe, it, expect, vi } from 'vitest'
import { createClient } from '../../src/client.js'
import { dedupePlugin } from '../../src/plugins/dedupe.js'
import { defaultDelay } from '../../src/retry.js'
describe('client hooks and error handling', () => {
it('calls onTimeout and throws TimeoutError when timeout signal aborts', async () => {
let timeoutCalled = false
global.fetch = vi.fn().mockImplementation(async (input) => {
const signal = input instanceof Request ? input.signal : undefined
return await new Promise((_resolve, reject) => {
if (signal?.aborted) {
reject(new DOMException('aborted', 'AbortError'))
return
}
signal?.addEventListener(
'abort',
() => reject(new DOMException('aborted', 'AbortError')),
{ once: true }
)
})
})
const client = createClient({
timeout: 10,
hooks: {
onTimeout: () => {
timeoutCalled = true
},
},
})
await expect(client('http://timeout-hook')).rejects.toThrow('timed out')
expect(timeoutCalled).toBe(true)
}, 1000)
it('calls onAbort and throws AbortError when user aborts', async () => {
let abortCalled = false
global.fetch = vi.fn().mockImplementation(async () => {
await new Promise((resolve) => setTimeout(resolve, 10))
return new Response('abort', { status: 200 })
})
const controller = new AbortController()
const client = createClient({
hooks: {
onAbort: () => {
abortCalled = true
},
},
})
controller.abort()
await expect(
client('http://abort-hook', { signal: controller.signal })
).rejects.toThrow('aborted')
expect(abortCalled).toBe(true)
})
it('returns last response if error occurs after response', async () => {
global.fetch = vi.fn().mockImplementation(async () => {
return new Response('ok', { status: 200 })
})
const client = createClient({
throwOnHttpError: true,
hooks: {
transformResponse: async () => {
throw new Error('fail after response')
},
},
})
const res = await client('http://last-response')
expect(res.status).toBe(200)
expect(await res.text()).toBe('ok')
})
})
describe('client branch coverage targets', () => {
it('passes undefined signal to dedupeHashFn when init.signal is null', async () => {
let seenSignal: AbortSignal | undefined = undefined
const client = createClient({
plugins: [
dedupePlugin({
hashFn: (params) => {
seenSignal = params.signal
return undefined
},
}),
],
fetchHandler: async () => new Response('ok', { status: 200 }),
})
await client('https://example.com/null-signal', {
signal: null as unknown as AbortSignal,
})
expect(seenSignal).toBeUndefined()
})
it('throws TimeoutError before fetch when timeout signal is already aborted', async () => {
const originalTimeout = AbortSignal.timeout
try {
AbortSignal.timeout = ((ms: number) => {
void ms
const c = new AbortController()
c.abort()
return c.signal
}) as typeof AbortSignal.timeout
const onTimeout = vi.fn()
global.fetch = vi.fn().mockImplementation(async () => {
throw new Error('fetch should not be called')
})
const client = createClient({ timeout: 10, hooks: { onTimeout } })
await expect(
client('https://example.com/pre-aborted-timeout')
).rejects.toThrow('signal timed out')
expect(onTimeout).toHaveBeenCalled()
expect(global.fetch).not.toHaveBeenCalled()
} finally {
AbortSignal.timeout = originalTimeout
}
})
it('uses no-throwIfAborted fallback and throws AbortError when user aborts mid-check', async () => {
const originalThrowIfAborted = AbortSignal.prototype.throwIfAborted
const originalAny = AbortSignal.any
try {
// @ts-expect-error coverage: force fallback branch
AbortSignal.prototype.throwIfAborted = undefined
const userController = new AbortController()
AbortSignal.any = ((signals: AbortSignal[]) => {
void signals
return {
get aborted() {
userController.abort()
return true
},
} as AbortSignal
}) as typeof AbortSignal.any
global.fetch = vi.fn().mockImplementation(async () => {
throw new Error('fetch should not be called')
})
const onAbort = vi.fn()
const client = createClient({ timeout: 60, hooks: { onAbort } })
await expect(
client('https://example.com/fallback-user-abort', {
signal: userController.signal,
})
).rejects.toThrow('Request was aborted by user')
expect(onAbort).toHaveBeenCalled()
expect(global.fetch).not.toHaveBeenCalled()
} finally {
AbortSignal.any = originalAny
AbortSignal.prototype.throwIfAborted = originalThrowIfAborted
}
})
it('uses no-throwIfAborted fallback and throws TimeoutError when timeout aborts mid-check', async () => {
const originalThrowIfAborted = AbortSignal.prototype.throwIfAborted
const originalAny = AbortSignal.any
const originalTimeout = AbortSignal.timeout
try {
// @ts-expect-error coverage: force fallback branch
AbortSignal.prototype.throwIfAborted = undefined
let timeoutAborted = false
AbortSignal.timeout = ((ms: number) => {
void ms
return {
get aborted() {
return timeoutAborted
},
} as AbortSignal
}) as typeof AbortSignal.timeout
AbortSignal.any = ((signals: AbortSignal[]) => {
void signals
return {
get aborted() {
timeoutAborted = true
return true
},
} as AbortSignal
}) as typeof AbortSignal.any
const onTimeout = vi.fn()
global.fetch = vi.fn().mockImplementation(async () => {
throw new Error('fetch should not be called')
})
const client = createClient({ timeout: 10, hooks: { onTimeout } })
await expect(
client('https://example.com/fallback-timeout-abort')
).rejects.toThrow('signal timed out')
expect(onTimeout).toHaveBeenCalled()
expect(global.fetch).not.toHaveBeenCalled()
} finally {
AbortSignal.timeout = originalTimeout
AbortSignal.any = originalAny
AbortSignal.prototype.throwIfAborted = originalThrowIfAborted
}
})
})
// Suppress unhandled promise rejections globally for this test file
it('aborts after 50 ms', async () => {
const controller = new AbortController()
controller.abort() // Abort before request
global.fetch = vi.fn().mockImplementation(async (_input) => {
// fetch should never be called if signal is already aborted
throw new Error('fetch should not be called')
})
const f = createClient()
try {
await f('https://example.com', { signal: controller.signal })
throw new Error('Expected AbortError to be thrown')
} catch (err) {
expect(err).toBeInstanceOf(Error)
if (err instanceof Error) {
expect(err.name).toBe('AbortError')
expect(err.message).toBe('Request was aborted by user')
}
}
})
it('works with manual timeout implementation when AbortSignal.timeout is missing', async () => {
const origTimeout = AbortSignal.timeout
// @ts-expect-error: Simulate missing AbortSignal.timeout for coverage
AbortSignal.timeout = undefined
try {
global.fetch = vi.fn().mockImplementation(async (input) => {
const signal = input instanceof Request ? input.signal : undefined
return await new Promise((_resolve, reject) => {
if (signal && signal.aborted) {
reject(new DOMException('aborted', 'AbortError'))
} else if (signal) {
signal.addEventListener('abort', () => {
reject(new DOMException('aborted', 'AbortError'))
})
}
// Never resolve (simulate hanging request)
})
})
const client = createClient({ timeout: 50 })
await expect(client('http://example.com')).rejects.toThrow()
} finally {
AbortSignal.timeout = origTimeout
}
})
it('throws AbortError with message "Request was aborted" when timeout signal aborts', async () => {
const transformedController = new AbortController()
global.fetch = vi.fn().mockImplementation(async (input) => {
const signal = input instanceof Request ? input.signal : undefined
return await new Promise((_resolve, reject) => {
if (signal && signal.aborted) {
reject(new DOMException('aborted', 'AbortError'))
} else if (signal) {
signal.addEventListener('abort', () => {
reject(new DOMException('aborted', 'AbortError'))
})
}
// Never resolve (simulate hanging request)
})
})
transformedController.abort() // Abort before request starts
// Simulate environment without throwIfAborted
const origThrowIfAborted = AbortSignal.prototype.throwIfAborted
// @ts-expect-error: Simulate environment without throwIfAborted for coverage
AbortSignal.prototype.throwIfAborted = undefined
global.fetch = vi.fn().mockImplementation(async (_input) => {
throw new Error('fetch should not be called if signal is already aborted')
})
const client = createClient({
hooks: {
transformRequest: (req) =>
new Request(req, { signal: transformedController.signal }),
},
// No timeout, no user signal
})
try {
await client('https://example.com')
throw new Error('Expected AbortError to be thrown')
} catch (err) {
if (err instanceof Error) {
expect(err.constructor.name).toBe('AbortError')
expect(err.name).toBe('AbortError')
expect(err.message).toBe('Request was aborted')
}
} finally {
// Restore throwIfAborted
AbortSignal.prototype.throwIfAborted = origThrowIfAborted
}
})
describe('retry', () => {
it('retries 2 times and then succeeds', async () => {
let calls = 0
global.fetch = vi.fn().mockImplementation(async () => {
calls++
if (calls < 3) throw new Error('network down')
return new Response(JSON.stringify({ ok: true }), { status: 200 })
})
const f = createClient({ retries: 2 })
const res = await f('https://example.com')
expect(res.status).toBe(200)
expect(calls).toBe(3) // 1 initial + 2 retries
})
it('throws after 3 failures', async () => {
global.fetch = vi.fn().mockRejectedValue(new Error('boom'))
const f = createClient({ retries: 2 })
await expect(f('https://example.com')).rejects.toThrow('boom')
expect(global.fetch).toHaveBeenCalledTimes(3)
})
it('retries a POST request with a JSON body — succeeds on second attempt', async () => {
// Regression: without the fix, the retry throws
// "Cannot construct a Request with a Request object that has already been used."
// because the body of the original Request is consumed on the first attempt.
let calls = 0
global.fetch = vi.fn().mockImplementation(async () => {
calls++
if (calls === 1) return new Response('upstream error', { status: 500 })
return new Response('ok', { status: 200 })
})
const f = createClient({ retries: 1 })
const res = await f('https://example.com/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' }),
})
expect(res.status).toBe(200)
expect(calls).toBe(2)
})
it('retries a POST request with a JSON body — all attempts return 500, no TypeError thrown', async () => {
// Regression: without the fix, the second attempt throws TypeError instead of
// returning the upstream 500 response.
let calls = 0
global.fetch = vi.fn().mockImplementation(async () => {
calls++
return new Response('upstream error', { status: 500 })
})
const f = createClient({ retries: 2 })
const res = await f('https://example.com/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' }),
})
expect(res.status).toBe(500)
expect(calls).toBe(3)
})
})
describe('retry with shouldRetry', () => {
it('retries network error', async () => {
let calls = 0
global.fetch = vi
.fn()
.mockImplementation(() =>
++calls < 3
? Promise.reject(new Error('fail'))
: Promise.resolve(new Response())
)
const f = createClient({ retries: 2 })
const res = await f('https://example.com') // will succeed
expect(res.status).toBe(200)
expect(global.fetch).toHaveBeenCalledTimes(3)
})
it('does NOT retry 400', async () => {
global.fetch = vi.fn().mockResolvedValue(new Response('', { status: 400 }))
const f = createClient({ retries: 2 })
const res = await f('https://example.com')
expect(res.status).toBe(400)
expect(global.fetch).toHaveBeenCalledTimes(1) // only once
})
})
describe('custom shouldRetry', () => {
it('uses custom retry policy and retries only once', async () => {
// custom policy that only retries on 503
const customShouldRetry = (
ctx: import('../../src/types').RetryContext
): boolean => {
if (ctx.response) {
return ctx.response.status === 503
}
return false
}
// mock fetch that returns 503 then 200
let calls = 0
global.fetch = vi.fn().mockImplementation(async () => {
calls++
if (calls === 1) {
return new Response('', { status: 503 })
}
return new Response('success', { status: 200 }) // second call succeeds
})
// create client with custom policy and retries: 1
const f = createClient({ retries: 2, shouldRetry: customShouldRetry })
// call and expect a resolved Response with status 200 after retry
const res = await f('https://example.com')
expect(res.status).toBe(200)
expect(global.fetch).toHaveBeenCalledTimes(2) // 1 retry
})
it('uses default retry policy and retries on 500', async () => {
// mock fetch that returns 500 then 200
let calls = 0
global.fetch = vi.fn().mockImplementation(async () => {
calls++
if (calls === 1) {
return new Response('', { status: 500 }) // first call returns 500
}
return new Response('success', { status: 200 }) // second call succeeds
})
// create client with default policy and retries: 1
const f = createClient({ retries: 1 })
// call and expect a resolved Response with status 200 after retry
const res = await f('https://example.com')
expect(res.status).toBe(200)
expect(global.fetch).toHaveBeenCalledTimes(2) // 1 retry
})
it('does NOT retry on 400 with default policy', async () => {
// mock fetch that returns 400
global.fetch = vi.fn().mockResolvedValue(new Response('', { status: 400 }))
// create client with default policy and retries: 1
const f = createClient({ retries: 1 })
// call and expect a resolved Response with status 400
const res = await f('https://example.com')
expect(res.status).toBe(400)
expect(global.fetch).toHaveBeenCalledTimes(1) // no retry
})
})
describe('Retry-After header', () => {
it('respects Retry-After header (seconds)', () => {
const response = new Response('', { status: 429 })
Object.defineProperty(response, 'headers', {
value: {
get: (name: string) => (name === 'Retry-After' ? '2' : undefined),
},
})
const ctx = { attempt: 1, request: new Request('x'), response }
const delay =
typeof defaultDelay === 'function' ? defaultDelay(ctx) : defaultDelay
expect(delay).toBe(2000)
})
it('respects Retry-After header (date)', () => {
// Mock Date.now for deterministic test
const fixedNow = 2000000000000 // some fixed timestamp
const originalNow = Date.now
Date.now = () => fixedNow
try {
const date = new Date(fixedNow + 5000).toUTCString()
const response = new Response('', { status: 429 })
Object.defineProperty(response, 'headers', {
value: {
get: (name: string) => (name === 'Retry-After' ? date : undefined),
},
})
const ctx = { attempt: 1, request: new Request('x'), response }
const delay =
typeof defaultDelay === 'function' ? defaultDelay(ctx) : defaultDelay
expect(delay).toBe(5000)
} finally {
Date.now = originalNow
}
})
it('timeout: 0 disables timeout', async () => {
global.fetch = vi.fn().mockImplementation(async () => {
// Simulate a request that takes longer than normal timeout would allow
await new Promise((resolve) => setTimeout(resolve, 100))
return new Response('success')
})
const client = createClient({ timeout: 0 })
const response = await client('https://example.com')
expect(response.status).toBe(200)
expect(await response.text()).toBe('success')
})
})
it('should throw if AbortSignal.any is missing and multiple signals are present', async () => {
const origAny = AbortSignal.any
// Remove AbortSignal.any
// @ts-expect-error: Simulate missing AbortSignal.any for coverage
AbortSignal.any = undefined
const controller1 = new AbortController()
const controller2 = new AbortController()
// Use transformRequest to add a second signal
const client = createClient({
hooks: {
transformRequest: (req) =>
new Request(req, { signal: controller2.signal }),
},
})
await expect(
client('https://example.com', { signal: controller1.signal, timeout: 1 })
).rejects.toThrow(/AbortSignal.any is required/)
// Restore AbortSignal.any
AbortSignal.any = origAny
})
it('dedupes identical requests and returns the same promise', async () => {
let fetchCalls = 0
const response = new Response('deduped', { status: 200 })
global.fetch = vi.fn().mockImplementation(async () => {
fetchCalls++
// Simulate network delay
await new Promise((resolve) => setTimeout(resolve, 10))
return response
})
const client = createClient({ plugins: [dedupePlugin()] })
// Fire two requests with identical params
const p1 = client('https://dedupe-test.com', { method: 'GET' })
const p2 = client('https://dedupe-test.com', { method: 'GET' })
// Both should resolve to the same Response object
const [r1, r2] = await Promise.all([p1, p2])
expect(fetchCalls).toBe(1)
expect(r1.status).toBe(200)
expect(r2.status).toBe(200)
expect(await r1.text()).toBe('deduped')
})
it('dedupes identical requests that return HTTP error responses', async () => {
let fetchCalls = 0
global.fetch = vi.fn().mockImplementation(async () => {
fetchCalls++
return new Response('fail', { status: 500 })
})
const client = createClient({ plugins: [dedupePlugin()] })
// Fire two requests with identical params
const p1 = client('https://dedupe-reject.com', { method: 'GET' })
const p2 = client('https://dedupe-reject.com', { method: 'GET' })
const [r1, r2] = await Promise.all([p1, p2])
expect(r1.status).toBe(500)
expect(r2.status).toBe(500)
expect(fetchCalls).toBe(1)
})
describe('dedupe cache TTL and sweeper', () => {
const delay = (ms: number) => new Promise((res) => setTimeout(res, ms))
it('should invalidate dedupe cache after TTL expires', async () => {
let callCount = 0
const client = createClient({
plugins: [dedupePlugin({ ttl: 50, sweepInterval: 20 })],
fetchHandler: async (_input: RequestInfo | URL) => {
callCount++
await delay(10)
return new Response('ok', { status: 200 })
},
})
// First call, triggers fetch
const p1 = client('http://ttl-test')
// Second call, deduped
const p2 = client('http://ttl-test')
expect(p1).toStrictEqual(p2)
await p1
expect(callCount).toBe(1)
// Wait for TTL to expire
await delay(60)
// Third call, should not be deduped (cache expired)
const p3 = client('http://ttl-test')
await p3
expect(callCount).toBe(2)
})
it('should not reject deduped promises if TTL expires', async () => {
let resolveFetch: (v: Response) => void
const fetchPromise = new Promise<Response>((res) => {
resolveFetch = res
})
const client = createClient({
plugins: [dedupePlugin({ ttl: 30, sweepInterval: 10 })],
fetchHandler: async () => {
return await fetchPromise
},
})
const p1 = client('http://ttl-promise')
const p2 = client('http://ttl-promise')
expect(p1).toStrictEqual(p2)
// Wait for TTL to expire
await delay(40)
// Promise should still be pending, not rejected
let settled = false
p1.then(() => {
settled = true
})
await delay(10)
expect(settled).toBe(false)
// Now resolve the fetch
resolveFetch!(new Response('done', { status: 200 }))
await delay(10) // allow promise to settle
expect(settled).toBe(true)
})
it('should clean up dedupe entries when request settles', async () => {
const client = createClient({
plugins: [dedupePlugin({ ttl: 20, sweepInterval: 10 })],
fetchHandler: async () => {
return new Response('ok', { status: 200 })
},
})
await client('http://cleanup')
await delay(30) // Wait for TTL and sweeper
// No direct plugin internals are exposed; this is validated by behavior.
await expect(client('http://cleanup')).resolves.toBeInstanceOf(Response)
})
it('should dedupe even if dedupeTTL is 0 (no expiry)', async () => {
let callCount = 0
const client = createClient({
plugins: [dedupePlugin({ ttl: 0 })],
fetchHandler: async () => {
callCount++
return new Response('ok', { status: 200 })
},
})
const p1 = client('http://no-ttl')
const p2 = client('http://no-ttl')
expect(p1).toStrictEqual(p2)
await p1
expect(callCount).toBe(1)
})
})