|
1 | 1 | import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
2 | 2 | import { |
3 | 3 | fetchGitHubContributions, |
| 4 | + fetchWithRetry, |
4 | 5 | fetchUserProfile, |
5 | 6 | fetchUserRepos, |
6 | 7 | getFullDashboardData, |
@@ -60,6 +61,54 @@ afterEach(() => { |
60 | 61 | } |
61 | 62 | }); |
62 | 63 |
|
| 64 | +describe('fetchWithRetry', () => { |
| 65 | + beforeEach(() => { |
| 66 | + vi.spyOn(global, 'fetch'); |
| 67 | + }); |
| 68 | + |
| 69 | + afterEach(() => { |
| 70 | + vi.restoreAllMocks(); |
| 71 | + }); |
| 72 | + |
| 73 | + it('removes caller abort listeners after a successful request', async () => { |
| 74 | + const controller = new AbortController(); |
| 75 | + const addListenerSpy = vi.spyOn(controller.signal, 'addEventListener'); |
| 76 | + const removeListenerSpy = vi.spyOn(controller.signal, 'removeEventListener'); |
| 77 | + |
| 78 | + vi.mocked(fetch).mockResolvedValue(mockResponse({ ok: true })); |
| 79 | + |
| 80 | + await fetchWithRetry('https://api.github.com/test', { signal: controller.signal }, 0, 1000); |
| 81 | + |
| 82 | + const abortListener = addListenerSpy.mock.calls.find(([event]) => event === 'abort')?.[1]; |
| 83 | + |
| 84 | + expect(abortListener).toEqual(expect.any(Function)); |
| 85 | + expect(addListenerSpy).toHaveBeenCalledWith('abort', abortListener, { once: true }); |
| 86 | + expect(removeListenerSpy).toHaveBeenCalledWith('abort', abortListener); |
| 87 | + }); |
| 88 | + |
| 89 | + it('still aborts the in-flight request when the caller signal is aborted', async () => { |
| 90 | + const controller = new AbortController(); |
| 91 | + |
| 92 | + vi.mocked(fetch).mockImplementation( |
| 93 | + (_url: RequestInfo | URL, options?: RequestInit) => |
| 94 | + new Promise<Response>((_resolve, reject) => { |
| 95 | + options?.signal?.addEventListener( |
| 96 | + 'abort', |
| 97 | + () => reject(new DOMException('Aborted', 'AbortError')), |
| 98 | + { once: true } |
| 99 | + ); |
| 100 | + }) |
| 101 | + ); |
| 102 | + |
| 103 | + const request = fetchWithRetry('https://api.github.com/test', { signal: controller.signal }); |
| 104 | + |
| 105 | + controller.abort(); |
| 106 | + |
| 107 | + await expect(request).rejects.toThrow('Aborted'); |
| 108 | + expect(fetch).toHaveBeenCalledOnce(); |
| 109 | + }); |
| 110 | +}); |
| 111 | + |
63 | 112 | describe('fetchGitHubContributions', () => { |
64 | 113 | beforeEach(() => { |
65 | 114 | vi.spyOn(global, 'fetch'); |
|
0 commit comments