|
1 | 1 | import { default as waitForPromise } from './wait-for-promise.ts'; |
2 | 2 |
|
| 3 | +const props = [ |
| 4 | + 'body', |
| 5 | + 'bodyUsed', |
| 6 | + 'headers', |
| 7 | + 'ok', |
| 8 | + 'redirected', |
| 9 | + 'status', |
| 10 | + 'statusText', |
| 11 | + 'type', |
| 12 | + 'url', |
| 13 | +] as const satisfies (keyof Response)[]; |
| 14 | +type ResponseProp = (typeof props)[number]; |
| 15 | +function isResponseProperty(maybeProp: string): maybeProp is ResponseProp { |
| 16 | + return props.some((prop) => maybeProp === prop); |
| 17 | +} |
| 18 | + |
| 19 | +const fns = [ |
| 20 | + 'arrayBuffer', |
| 21 | + 'blob', |
| 22 | + 'bytes', |
| 23 | + 'clone', |
| 24 | + 'formData', |
| 25 | + 'json', |
| 26 | + 'text', |
| 27 | +] as const satisfies (keyof Response)[]; |
| 28 | +type ResponseFn = (typeof fns)[number]; |
| 29 | +function isResponseFn(maybeFn: string): maybeFn is ResponseFn { |
| 30 | + return fns.some((fn) => maybeFn === fn); |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Wraps the fetch promise in a test waiter, and also wraps the returned promises' async functions (like json()) in a |
| 35 | + * test waiter. |
| 36 | + */ |
3 | 37 | export async function waitForFetch(fetchPromise: ReturnType<typeof fetch>) { |
4 | 38 | const response = await waitForPromise(fetchPromise); |
5 | 39 |
|
6 | 40 | return new Proxy(response, { |
7 | 41 | get(target, prop, receiver) { |
| 42 | + /* Depending on the stack, Response is often already a Proxy. Reflect.get() will error for property values, when |
| 43 | + * using a Proxy as the _receiver_ arg, so just return the value the normal way to avoid that issue. */ |
| 44 | + if (typeof prop === 'string' && isResponseProperty(prop)) { |
| 45 | + return target[prop]; |
| 46 | + } |
8 | 47 | const original = Reflect.get(target, prop, receiver); |
9 | 48 |
|
10 | | - if ( |
11 | | - typeof prop === 'string' && |
12 | | - ['json', 'text', 'arrayBuffer', 'blob', 'formData', 'bytes'].includes(prop) |
13 | | - ) { |
| 49 | + // Wrap Response functions in test waiter |
| 50 | + if (typeof prop === 'string' && isResponseFn(prop)) { |
| 51 | + // clone() is sync, no need to wrap in test-waiter |
| 52 | + if (prop === 'clone') { |
| 53 | + return (...args: unknown[]) => { |
| 54 | + return original.call(target, ...args); |
| 55 | + }; |
| 56 | + } |
14 | 57 | return (...args: unknown[]) => { |
15 | 58 | return waitForPromise(original.call(target, ...args)); |
16 | 59 | }; |
17 | 60 | } |
18 | | - |
| 61 | + // return the Reflect.get() result for anything else |
19 | 62 | return original; |
20 | 63 | }, |
21 | 64 | }); |
|
0 commit comments