forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient-behavior.test.ts
More file actions
872 lines (795 loc) · 23 KB
/
Copy pathclient-behavior.test.ts
File metadata and controls
872 lines (795 loc) · 23 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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
import { describe, expect, it, vi } from 'vitest';
import {
BaseClient,
LilyAuthenticationError,
LilyApiError,
LilySdk,
createFetchHttpClient,
LilyTransportError,
resolveLilySdkConfig,
} from '../src/index';
import { createMockHttpClient } from './helpers/mock-http-client';
describe('client behavior', () => {
it('exposes transport primitives from the root entrypoint', () => {
expect(createFetchHttpClient).toBeInstanceOf(Function);
expect(BaseClient).toBeInstanceOf(Function);
});
it('allows subclassing BaseClient with a custom HTTP client', async () => {
const requestSpy = vi.fn(() =>
Promise.resolve({
status: 200,
headers: new Headers(),
data: { ok: true },
}),
);
class TestClient extends BaseClient {
async probe() {
return this.request<{ ok: boolean }>({ method: 'GET', path: '/probe' });
}
}
const client = new TestClient(createMockHttpClient(requestSpy));
const result = await client.probe();
expect(requestSpy).toHaveBeenCalledWith({ method: 'GET', path: '/probe' });
expect(result.ok).toBe(true);
});
it('calls system health endpoint through the system client', async () => {
const requestSpy = vi.fn(() =>
Promise.resolve({
status: 200,
headers: new Headers(),
data: {
status: 'ok',
version: '0.1.0',
timestamp: new Date().toISOString(),
checks: {
api: 'ok',
},
},
}),
);
const sdk = new LilySdk(
{
baseUrl: 'https://api.lily.test',
fetch: globalThis.fetch,
},
createMockHttpClient(requestSpy),
);
const health: HealthStatus = await sdk.system.health();
expect(requestSpy).toHaveBeenCalledWith({
method: 'GET',
path: '/v1/system/health',
});
expect(health).toEqual({
status: 'ok',
version: '0.1.0',
timestamp: expect.any(String),
checks: {
api: 'ok',
},
});
});
it('calls system info endpoint and returns service information', async () => {
const serviceInfo: ServiceInfo = {
name: 'lily-api',
version: '0.1.0',
environment: 'staging',
docsUrl: 'https://docs.lily.test',
};
const requestSpy = vi.fn(() =>
Promise.resolve({
status: 200,
headers: new Headers(),
data: serviceInfo,
}),
);
const sdk = new LilySdk(
{
baseUrl: 'https://api.lily.test',
fetch: globalThis.fetch,
},
createMockHttpClient(requestSpy),
);
const info: ServiceInfo = await sdk.system.info();
expect(requestSpy).toHaveBeenCalledWith({
method: 'GET',
path: '/v1/system/info',
});
expect(info).toEqual(serviceInfo);
});
it.each([
{
name: 'api key only',
credentials: { apiKey: 'secret-key' },
authHeaders: { 'x-api-key': 'secret-key' },
},
{
name: 'auth token only',
credentials: { authToken: 'secret-token' },
authHeaders: { authorization: 'Bearer secret-token' },
},
{
name: 'both credentials',
credentials: { apiKey: 'secret-key', authToken: 'secret-token' },
authHeaders: {
'x-api-key': 'secret-key',
authorization: 'Bearer secret-token',
},
},
{
name: 'no credentials',
credentials: {},
authHeaders: {},
},
])(
'forwards the correct auth headers with $name',
async ({ credentials, authHeaders }) => {
const fetchSpy = vi.fn((input: URL | RequestInfo, init?: RequestInit) => {
expect(input).toEqual(
new URL('https://api.lily.test/v1/system/health'),
);
expect(init?.method).toBe('GET');
return Promise.resolve(
new Response(null, {
status: 200,
}),
);
});
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: fetchSpy,
...credentials,
});
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
apiKey: 'secret-key',
authToken: 'secret-token',
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
validateResponses: false,
fetch: fetchSpy,
});
expect(fetchSpy).toHaveBeenCalledOnce();
expect(fetchSpy.mock.calls[0]?.[1]?.headers).toEqual({
accept: 'application/json',
'content-type': 'application/json',
'user-agent': 'lily-sdk/test',
...authHeaders,
});
},
);
it('maps authentication failures to a typed error with full payload', async () => {
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
validateResponses: false,
fetch: vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify({ message: 'nope', code: 'INVALID_TOKEN' }), {
status: 401,
headers: {
'content-type': 'application/json',
},
}),
),
),
});
try {
await httpClient.request({
method: 'GET',
path: '/v1/system/health',
});
expect.fail('should have thrown');
} catch (error) {
expect(error).toBeInstanceOf(LilyAuthenticationError);
const authError = error as LilyAuthenticationError;
expect(authError.request).toEqual({
method: 'GET',
path: '/v1/system/health',
url: 'https://api.lily.test/v1/system/health',
});
}
});
it('attaches request metadata to api errors', async () => {
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify({ message: 'fail' }), {
status: 500,
headers: {
'content-type': 'application/json',
},
}),
),
),
});
try {
await httpClient.request({
method: 'GET',
path: '/v1/items',
});
expect.fail('should have thrown');
} catch (error) {
expect(error).toBeInstanceOf(LilyApiError);
const apiError = error as LilyApiError;
expect(apiError.request).toEqual({
method: 'GET',
path: '/v1/items',
url: 'https://api.lily.test/v1/items',
});
}
});
it('attaches request metadata to transport timeout errors', async () => {
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 10,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: vi.fn((...args: unknown[]) => {
const init = args[1] as RequestInit | undefined;
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
const abortError = new Error('The operation was aborted');
abortError.name = 'AbortError';
reject(abortError);
});
});
}),
});
try {
await httpClient.request({
method: 'GET',
path: '/v1/system/health',
});
expect.fail('request should have thrown');
} catch (error) {
expect(error).toBeInstanceOf(LilyTransportError);
const transportError = error as LilyTransportError;
expect(transportError.code).toBe('TIMEOUT');
expect(transportError.request).toEqual({
method: 'GET',
path: '/v1/system/health',
url: 'https://api.lily.test/v1/system/health',
});
}
});
it('propagates full error payload on non-retryable API errors', async () => {
const errorBody = {
code: 'INVALID_REQUEST',
message: 'Missing required field',
field: 'amount',
};
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify(errorBody), {
status: 400,
headers: {
'content-type': 'application/json',
},
}),
),
),
});
try {
await httpClient.request({
method: 'POST',
path: '/v1/payments',
body: {},
});
expect.fail('Expected LilyApiError to be thrown');
} catch (error) {
expect(error).toBeInstanceOf(LilyApiError);
const apiError = error as LilyApiError;
expect(apiError.statusCode).toBe(400);
expect(apiError.code).toBe('API_ERROR');
expect(apiError.details).toEqual(errorBody);
}
});
describe.each([
{
scenario: 'apiKey only',
config: { apiKey: 'my-api-key' },
expectedHeaders: { 'x-api-key': 'my-api-key' },
disallowedHeaders: ['authorization'],
},
{
scenario: 'authToken only',
config: { authToken: 'my-token' },
expectedHeaders: { authorization: 'Bearer my-token' },
disallowedHeaders: ['x-api-key'],
},
{
scenario: 'both apiKey and authToken',
config: { apiKey: 'my-api-key', authToken: 'my-token' },
expectedHeaders: {
authorization: 'Bearer my-token',
'x-api-key': 'my-api-key',
},
disallowedHeaders: [],
},
{
scenario: 'neither credential',
config: {},
expectedHeaders: {},
disallowedHeaders: ['authorization', 'x-api-key'],
},
])('auth credential forwarding ($scenario)', ({ config, expectedHeaders, disallowedHeaders }) => {
it(`forwards the expected authentication headers for ${config}`, async () => {
const fetchSpy = vi.fn((_input: URL | RequestInfo, init?: RequestInit) => {
const headers = (init?.headers ?? {}) as Record<string, string>;
for (const [key, value] of Object.entries(expectedHeaders)) {
expect(headers[key]).toBe(value);
}
for (const key of disallowedHeaders) {
expect(headers[key]).toBeUndefined();
}
return Promise.resolve(
new Response(
JSON.stringify({ status: 'ok' }),
{
status: 200,
headers: { 'content-type': 'application/json' },
},
),
);
});
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
...config,
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: fetchSpy,
});
const response = await httpClient.request({
method: 'GET',
path: '/v1/system/health',
});
expect(response.status).toBe(200);
expect(fetchSpy).toHaveBeenCalledOnce();
});
});
it('merges defaultHeaders with per-request headers', async () => {
const fetchSpy = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
expect(init?.headers).toMatchObject({
accept: 'application/json',
'content-type': 'application/json',
'user-agent': 'lily-sdk/test',
'x-tenant': 'acme',
'x-request-id': 'req-123',
});
return Promise.resolve(
new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: {
'content-type': 'application/json',
},
}),
);
});
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {
'x-tenant': 'acme',
},
userAgent: 'lily-sdk/test',
fetch: fetchSpy,
});
await httpClient.request({
method: 'GET',
path: '/v1/items',
headers: {
'x-request-id': 'req-123',
},
});
expect(fetchSpy).toHaveBeenCalledOnce();
});
it('allows per-request headers to override defaultHeaders', async () => {
const fetchSpy = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
expect(init?.headers).toMatchObject({
'x-tenant': 'override',
});
return Promise.resolve(
new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: {
'content-type': 'application/json',
},
}),
);
});
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {
'x-tenant': 'acme',
},
userAgent: 'lily-sdk/test',
fetch: fetchSpy,
});
await httpClient.request({
method: 'GET',
path: '/v1/items',
headers: {
'x-tenant': 'override',
},
});
expect(fetchSpy).toHaveBeenCalledOnce();
});
it('does not retry POST requests on retryable statuses', async () => {
const fetchSpy = vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify({ message: 'fail' }), {
status: 500,
headers: {
'content-type': 'application/json',
},
}),
),
);
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 3,
retryDelayMs: 0,
retryableStatusCodes: [408, 409, 425, 429, 500, 502, 503, 504],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: fetchSpy,
});
try {
await httpClient.request({
method: 'POST',
path: '/v1/payments',
});
expect.fail('should have thrown');
} catch (error) {
expect(error).toBeInstanceOf(LilyApiError);
const apiError = error as LilyApiError;
expect(apiError.statusCode).toBe(500);
}
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
it('retries GET requests on retryable statuses', async () => {
const fetchSpy = vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify({ message: 'fail' }), {
status: 500,
headers: {
'content-type': 'application/json',
},
}),
),
);
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 2,
retryDelayMs: 0,
retryableStatusCodes: [408, 409, 425, 429, 500, 502, 503, 504],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: fetchSpy,
});
try {
await httpClient.request({
method: 'GET',
path: '/v1/items',
});
expect.fail('should have thrown');
} catch (error) {
expect(error).toBeInstanceOf(LilyApiError);
const apiError = error as LilyApiError;
expect(apiError.statusCode).toBe(500);
}
// Initial attempt + 2 retries = 3 total calls
expect(fetchSpy).toHaveBeenCalledTimes(3);
});
it('surfaces LilyApiError after retry exhaustion', async () => {
const fetchSpy = vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify({ message: 'unavailable' }), {
status: 503,
headers: {
'content-type': 'application/json',
},
}),
),
);
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 2,
retryDelayMs: 0,
retryableStatusCodes: [503],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: fetchSpy,
});
let caught: unknown;
try {
await httpClient.request({
method: 'GET',
path: '/v1/system/health',
});
} catch (error) {
caught = error;
}
expect(fetchSpy).toHaveBeenCalledTimes(3);
expect(caught).toBeInstanceOf(LilyApiError);
expect(caught).toMatchObject({ statusCode: 503 });
});
it('preserves the original fetch rejection as the transport error cause', async () => {
const networkError = new Error('connection refused');
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: vi.fn(() => Promise.reject(networkError)),
});
try {
await httpClient.request({
method: 'GET',
path: '/v1/system/health',
});
expect.unreachable('request should reject with LilyTransportError');
} catch (error) {
expect(error).toBeInstanceOf(LilyTransportError);
expect(error).toMatchObject({
code: 'TRANSPORT_ERROR',
cause: networkError,
});
}
});
it('preserves the AbortError as the timeout transport error cause', async () => {
let abortError: DOMException | undefined;
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 1,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: vi.fn(
(_input: URL | RequestInfo, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
abortError = new DOMException(
'The operation was aborted.',
'AbortError',
);
reject(abortError);
});
}),
),
});
try {
await httpClient.request({
method: 'GET',
path: '/v1/system/health',
});
expect.unreachable('request should reject with LilyTransportError');
} catch (error) {
expect(error).toBeInstanceOf(LilyTransportError);
expect(error).toMatchObject({
code: 'TIMEOUT',
cause: abortError,
});
}
});
describe('baseUrl path prefixes', () => {
async function requestedHref(
baseUrl: string,
path: string,
query?: Record<string, string | number | boolean | undefined>,
): Promise<string> {
const fetchSpy = vi.fn((_input: URL | RequestInfo) =>
Promise.resolve(
new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: {
'content-type': 'application/json',
},
}),
),
);
const httpClient = createFetchHttpClient(
resolveLilySdkConfig({
baseUrl,
fetch: fetchSpy,
}),
);
await httpClient.request({
method: 'GET',
path,
...(query === undefined ? {} : { query }),
});
expect(fetchSpy).toHaveBeenCalledOnce();
return String(fetchSpy.mock.calls[0]?.[0]);
}
it('keeps a path prefix when baseUrl has no trailing slash', async () => {
await expect(
requestedHref('https://host/lily/api', '/v1/system/health'),
).resolves.toBe('https://host/lily/api/v1/system/health');
});
it('keeps a path prefix when baseUrl already has a trailing slash', async () => {
await expect(
requestedHref('https://host/lily/api/', '/v1/system/health'),
).resolves.toBe('https://host/lily/api/v1/system/health');
});
it('joins request paths onto a host-root baseUrl', async () => {
await expect(
requestedHref('https://api.lily.test', '/v1/system/health'),
).resolves.toBe('https://api.lily.test/v1/system/health');
});
it('appends query parameters onto a path-prefixed URL', async () => {
await expect(
requestedHref('https://host/lily/api', '/v1/agents', {
limit: 10,
status: 'active',
}),
).resolves.toBe('https://host/lily/api/v1/agents?limit=10&status=active');
});
});
it('maps an empty JSON response to a validation error without retrying', async () => {
const fetchSpy = vi.fn(() =>
Promise.resolve(
new Response(null, {
status: 200,
headers: {
'content-type': 'application/json',
},
}),
),
);
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 2,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: fetchSpy,
});
const request = httpClient.request({
method: 'GET',
path: '/v1/system/health',
});
await expect(request).rejects.toMatchObject({
name: 'LilyValidationError',
code: 'RESPONSE_VALIDATION_ERROR',
statusCode: 200,
message:
'Failed to parse response body as JSON (status 200, content-type: application/json).',
} satisfies Partial<LilyValidationError>);
expect(fetchSpy).toHaveBeenCalledOnce();
});
it('surfaces the last API error after exhausting retries', async () => {
const fetchSpy = vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify({ message: 'unavailable' }), {
status: 503,
headers: {
'content-type': 'application/json',
},
}),
),
);
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 2,
retryDelayMs: 0,
retryableStatusCodes: [503],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: fetchSpy,
});
const error = await httpClient
.request({
method: 'GET',
path: '/v1/system/health',
})
.catch((reason: unknown) => reason);
expect(error).toBeInstanceOf(LilyApiError);
expect(error).toMatchObject({ statusCode: 503 });
expect(fetchSpy).toHaveBeenCalledTimes(3);
});
});
function createTestHttpClient(
fetch: typeof globalThis.fetch,
timeoutMs = 2_000,
) {
return createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch,
});
}