forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.test.ts
More file actions
83 lines (62 loc) · 2.44 KB
/
Copy pathclient.test.ts
File metadata and controls
83 lines (62 loc) · 2.44 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
import { fetchWithTimeout } from '../client';
// Mock global fetch
const mockFetch = jest.fn();
global.fetch = mockFetch;
describe('fetchWithTimeout', () => {
beforeEach(() => {
mockFetch.mockReset();
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('should resolve when fetch completes before timeout', async () => {
const mockResponse = new Response('ok');
mockFetch.mockResolvedValue(mockResponse);
const promise = fetchWithTimeout('https://example.com', { timeout: 1000 });
// Fetch resolves immediately in this mock, so no timer advancement needed
const result = await promise;
expect(result).toBe(mockResponse);
expect(mockFetch).toHaveBeenCalledWith(
'https://example.com',
expect.objectContaining({ signal: expect.any(AbortSignal) })
);
});
it('should abort when timeout elapses before fetch completes', async () => {
let capturedSignal: AbortSignal | null = null;
mockFetch.mockImplementation((_url: string, init?: RequestInit) => {
capturedSignal = init?.signal as AbortSignal;
return new Promise(() => {}); // Never resolves
});
const promise = fetchWithTimeout('https://example.com', { timeout: 500 });
// Advance timers past the timeout
jest.advanceTimersByTime(600);
await expect(promise).rejects.toThrow();
expect(capturedSignal?.aborted).toBe(true);
});
it('should compose caller-provided signal with internal timeout', async () => {
const callerController = new AbortController();
let capturedSignal: AbortSignal | null = null;
mockFetch.mockImplementation((_url: string, init?: RequestInit) => {
capturedSignal = init?.signal as AbortSignal;
return new Promise(() => {});
});
const promise = fetchWithTimeout('https://example.com', {
timeout: 5000,
signal: callerController.signal
});
// Caller cancels before timeout
callerController.abort();
await expect(promise).rejects.toThrow();
expect(capturedSignal?.aborted).toBe(true);
});
it('should use default timeout of 10s when not specified', async () => {
mockFetch.mockImplementation(() => new Promise(() => {}));
const promise = fetchWithTimeout('https://example.com');
// Should not abort before 10s
jest.advanceTimersByTime(9999);
// Still pending
jest.advanceTimersByTime(2);
await expect(promise).rejects.toThrow();
});
});