- Extracted fetch mocking logic into reusable `hookFetch()` utility function with middleware-style handler pattern. - Replaced manual `globalThis.fetch` assignment and restoration across 10 test files with `hookFetch()` calls using `using` statement for automatic cleanup. - Implemented Disposable pattern with Symbol.dispose for fetch hook resource management, eliminating try-finally blocks. - Exported `hookFetch` from utils public API to enable consistent fetch mocking across packages.
31 lines
793 B
TypeScript
31 lines
793 B
TypeScript
/**
|
|
* Intercept `globalThis.fetch` with a middleware-style handler.
|
|
*
|
|
* Returns a `Disposable` so callers can use `using` for automatic cleanup:
|
|
*
|
|
* ```ts
|
|
* using _hook = hookFetch((input, init, next) => {
|
|
* if (shouldIntercept(input)) {
|
|
* return new Response("mocked");
|
|
* }
|
|
* return next(input, init);
|
|
* });
|
|
* ```
|
|
*/
|
|
export type FetchHandler = (
|
|
input: string | URL | Request,
|
|
init: RequestInit | undefined,
|
|
next: typeof fetch,
|
|
) => Response | Promise<Response>;
|
|
|
|
export function hookFetch(handler: FetchHandler): Disposable {
|
|
const original = globalThis.fetch;
|
|
globalThis.fetch = ((input: string | URL | Request, init?: RequestInit) =>
|
|
handler(input, init, original)) as typeof fetch;
|
|
return {
|
|
[Symbol.dispose]() {
|
|
globalThis.fetch = original;
|
|
},
|
|
};
|
|
}
|