fix: keep browser fetch helper under test support

This commit is contained in:
Peter Steinberger
2026-04-29 08:46:20 +01:00
parent a62c7e5a27
commit ca972f692f
2 changed files with 30 additions and 31 deletions

View File

@@ -1,30 +0,0 @@
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");
}

View File

@@ -1 +1,30 @@
export { getBrowserTestFetch, type BrowserTestFetch } from "../test-support-fetch.js";
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");
}