test(browser): keep undici fetch helper test-only

This commit is contained in:
Vincent Koc
2026-04-29 00:28:02 -07:00
parent bd5afadc5c
commit c01244e859
2 changed files with 31 additions and 30 deletions

View File

@@ -1,30 +1 @@
import { createRequire } from "node:module";
type FetchLike = ((input: string | URL, init?: RequestInit) => Promise<Response>) & {
mock?: unknown;
};
export type BrowserTestFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
function isUsableFetch(value: unknown): value is FetchLike {
return typeof value === "function" && !("mock" in (value as FetchLike));
}
export function getBrowserTestFetch(): BrowserTestFetch {
const require = createRequire(import.meta.url);
const vitest = (globalThis as { vi?: { doUnmock?: (id: string) => void } }).vi;
vitest?.doUnmock?.("undici");
try {
delete require.cache[require.resolve("undici")];
} catch {
// Best-effort cache bust for shared-thread test workers.
}
const { fetch } = require("undici") as typeof import("undici");
if (isUsableFetch(fetch)) {
return (input, init) => fetch(input, init);
}
if (isUsableFetch(globalThis.fetch)) {
return (input, init) => globalThis.fetch(input, init);
}
throw new TypeError("fetch is not a function");
}
export { getBrowserTestFetch, type BrowserTestFetch } from "./test-support-fetch.js";

View File

@@ -0,0 +1,30 @@
import { createRequire } from "node:module";
type FetchLike = ((input: string | URL, init?: RequestInit) => Promise<Response>) & {
mock?: unknown;
};
export type BrowserTestFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
function isUsableFetch(value: unknown): value is FetchLike {
return typeof value === "function" && !("mock" in (value as FetchLike));
}
export function getBrowserTestFetch(): BrowserTestFetch {
const require = createRequire(import.meta.url);
const vitest = (globalThis as { vi?: { doUnmock?: (id: string) => void } }).vi;
vitest?.doUnmock?.("undici");
try {
delete require.cache[require.resolve("undici")];
} catch {
// Best-effort cache bust for shared-thread test workers.
}
const { fetch } = require("undici") as typeof import("undici");
if (isUsableFetch(fetch)) {
return (input, init) => fetch(input, init);
}
if (isUsableFetch(globalThis.fetch)) {
return (input, init) => globalThis.fetch(input, init);
}
throw new TypeError("fetch is not a function");
}