|
| 1 | +/** |
| 2 | + * @jest-environment jsdom |
| 3 | + */ |
| 4 | +/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 5 | +import '@testing-library/jest-dom'; |
| 6 | +import { act, render, screen, waitFor, cleanup } from '@testing-library/react'; |
| 7 | +import { fetchf } from '../../../src/index'; |
| 8 | +import { useFetcher } from '../../../src/react/index'; |
| 9 | +import { clearAllTimeouts } from '../../../src/timeout-wheel'; |
| 10 | + |
| 11 | +describe('fetchf deduplication and parking with jsdom and onRequest', () => { |
| 12 | + afterEach(() => { |
| 13 | + cleanup(); |
| 14 | + jest.restoreAllMocks(); |
| 15 | + clearAllTimeouts(); |
| 16 | + delete (window as any).__dedupeTriggered; |
| 17 | + }); |
| 18 | + |
| 19 | + it('deduplicates and parks requests when onRequest triggers a second identical fetchf call', async () => { |
| 20 | + const testUrl = '/api/onrequest-dedupe'; |
| 21 | + const cacheKey = 'onrequest-dedupe-key'; |
| 22 | + let resolveFetch: ((value: Response) => void) | undefined; |
| 23 | + let fetchCallCount = 0; |
| 24 | + |
| 25 | + // Mock global.fetch to simulate slow network |
| 26 | + global.fetch = jest.fn().mockImplementation(() => { |
| 27 | + fetchCallCount++; |
| 28 | + return new Promise<Response>((resolve) => { |
| 29 | + resolveFetch = resolve; |
| 30 | + }); |
| 31 | + }); |
| 32 | + |
| 33 | + // Track results from both calls |
| 34 | + let onRequestResult: any = undefined; |
| 35 | + |
| 36 | + // Set up onRequest interceptor that triggers a second fetchf call |
| 37 | + const onRequest = async (config: any) => { |
| 38 | + if (!onRequestResult) { |
| 39 | + // Trigger a second fetchf with the same cacheKey while the first is in-flight |
| 40 | + onRequestResult = fetchf(testUrl, { |
| 41 | + cacheKey, |
| 42 | + dedupeTime: 2000, |
| 43 | + }); |
| 44 | + } |
| 45 | + return config; |
| 46 | + }; |
| 47 | + |
| 48 | + // Start first request with onRequest interceptor |
| 49 | + const promise1 = fetchf(testUrl, { |
| 50 | + cacheKey, |
| 51 | + dedupeTime: 2000, |
| 52 | + onRequest, |
| 53 | + }); |
| 54 | + |
| 55 | + expect(promise1).not.toBeUndefined(); |
| 56 | + |
| 57 | + // Allow microtasks to flush so onRequest fires and the first doRequestOnce calls fetch() |
| 58 | + await act(async () => { |
| 59 | + await new Promise((r) => setTimeout(r, 0)); |
| 60 | + }); |
| 61 | + |
| 62 | + // onRequest triggered a second fetchf that was deduped |
| 63 | + expect(onRequestResult).not.toBeUndefined(); |
| 64 | + expect(promise1).not.toBe(onRequestResult); // Different promise objects, but parked |
| 65 | + |
| 66 | + // Only one actual fetch call should have been made (the second was deduped) |
| 67 | + expect(fetchCallCount).toBe(1); |
| 68 | + |
| 69 | + // Resolve the fetch with a proper mock response |
| 70 | + await act(async () => { |
| 71 | + if (resolveFetch) { |
| 72 | + resolveFetch({ |
| 73 | + ok: true, |
| 74 | + status: 200, |
| 75 | + data: { result: 'deduped-onrequest' }, |
| 76 | + body: JSON.stringify({ result: 'deduped-onrequest' }), |
| 77 | + headers: { 'content-type': 'application/json' }, |
| 78 | + } as unknown as Response); |
| 79 | + } |
| 80 | + }); |
| 81 | + |
| 82 | + // Both promises should resolve to the same result |
| 83 | + const [result1, result2] = await Promise.all([promise1, onRequestResult]); |
| 84 | + expect(result1.data).toEqual({ result: 'deduped-onrequest' }); |
| 85 | + expect(result2.data).toEqual({ result: 'deduped-onrequest' }); |
| 86 | + expect(fetchCallCount).toBe(1); |
| 87 | + }); |
| 88 | + |
| 89 | + it('useFetcher deduplication: onRequest triggers fetchf with same cacheKey, other useFetcher waits for it', async () => { |
| 90 | + const testUrl = '/api/component-dedupe'; |
| 91 | + const cacheKey = 'component-dedupe-key'; |
| 92 | + let resolveFetch: ((value: Response) => void) | undefined; |
| 93 | + let fetchCallCount = 0; |
| 94 | + |
| 95 | + // Mock global.fetch to simulate slow network |
| 96 | + global.fetch = jest.fn().mockImplementation(() => { |
| 97 | + fetchCallCount++; |
| 98 | + return new Promise<Response>((resolve) => { |
| 99 | + resolveFetch = resolve; |
| 100 | + }); |
| 101 | + }); |
| 102 | + |
| 103 | + // React test component that triggers the fetch |
| 104 | + function DedupeComponent() { |
| 105 | + const { data, isLoading } = useFetcher(testUrl, { |
| 106 | + cacheKey, |
| 107 | + dedupeTime: 2000, |
| 108 | + immediate: true, |
| 109 | + onRequest: async (config: any) => { |
| 110 | + // Only trigger once to avoid infinite loop |
| 111 | + if (!(window as any).__dedupeTriggered) { |
| 112 | + (window as any).__dedupeTriggered = true; |
| 113 | + // This fetchf call uses the same cacheKey and should be deduped |
| 114 | + fetchf(testUrl, { cacheKey, dedupeTime: 2000 }); |
| 115 | + } |
| 116 | + return config; |
| 117 | + }, |
| 118 | + }); |
| 119 | + return ( |
| 120 | + <div> |
| 121 | + <div data-testid="data"> |
| 122 | + {data ? JSON.stringify(data) : 'No Data'} |
| 123 | + </div> |
| 124 | + <div data-testid="loading"> |
| 125 | + {isLoading ? 'Loading' : 'Not Loading'} |
| 126 | + </div> |
| 127 | + </div> |
| 128 | + ); |
| 129 | + } |
| 130 | + |
| 131 | + // Another useFetcher instance that relies on the same cacheKey |
| 132 | + function WaitingComponent() { |
| 133 | + const { data, isLoading } = useFetcher(testUrl, { |
| 134 | + cacheKey, |
| 135 | + dedupeTime: 2000, |
| 136 | + immediate: true, |
| 137 | + }); |
| 138 | + return ( |
| 139 | + <div> |
| 140 | + <div data-testid="waiting-data"> |
| 141 | + {data ? JSON.stringify(data) : 'No Data'} |
| 142 | + </div> |
| 143 | + <div data-testid="waiting-loading"> |
| 144 | + {isLoading ? 'Loading' : 'Not Loading'} |
| 145 | + </div> |
| 146 | + </div> |
| 147 | + ); |
| 148 | + } |
| 149 | + |
| 150 | + // Render both components |
| 151 | + render( |
| 152 | + <> |
| 153 | + <DedupeComponent /> |
| 154 | + <WaitingComponent /> |
| 155 | + </>, |
| 156 | + ); |
| 157 | + |
| 158 | + // Both should be loading initially |
| 159 | + expect(screen.getByTestId('loading').textContent).toBe('Loading'); |
| 160 | + expect(screen.getByTestId('waiting-loading').textContent).toBe('Loading'); |
| 161 | + |
| 162 | + // Allow microtasks to flush so the fetch is actually called |
| 163 | + await act(async () => { |
| 164 | + await new Promise((r) => setTimeout(r, 0)); |
| 165 | + }); |
| 166 | + |
| 167 | + expect(fetchCallCount).toBe(1); |
| 168 | + |
| 169 | + // Resolve the fetch with a proper mock response |
| 170 | + await act(async () => { |
| 171 | + if (resolveFetch) { |
| 172 | + resolveFetch({ |
| 173 | + ok: true, |
| 174 | + status: 200, |
| 175 | + data: { result: 'deduped-component' }, |
| 176 | + body: JSON.stringify({ result: 'deduped-component' }), |
| 177 | + headers: { 'content-type': 'application/json' }, |
| 178 | + } as unknown as Response); |
| 179 | + } |
| 180 | + }); |
| 181 | + |
| 182 | + // Both should show the result and not loading |
| 183 | + await waitFor(() => { |
| 184 | + expect(screen.getByTestId('data').textContent).toContain( |
| 185 | + 'deduped-component', |
| 186 | + ); |
| 187 | + expect(screen.getByTestId('loading').textContent).toBe('Not Loading'); |
| 188 | + expect(screen.getByTestId('waiting-data').textContent).toContain( |
| 189 | + 'deduped-component', |
| 190 | + ); |
| 191 | + expect(screen.getByTestId('waiting-loading').textContent).toBe( |
| 192 | + 'Not Loading', |
| 193 | + ); |
| 194 | + }); |
| 195 | + |
| 196 | + // Only one network request should have been made |
| 197 | + expect(fetchCallCount).toBe(1); |
| 198 | + }); |
| 199 | +}); |
0 commit comments