在使用 API 时,Miniflare 允许你使用 undici 的 MockAgent API ↗ 为 fetch() 调用替换自定义的 Response。这对于测试向其他服务发起 HTTP 请求的 Worker 很有用。要启用 fetch mock,请使用 createFetchMock() 函数创建一个 MockAgent ↗,然后使用 fetchMock 选项设置它。
import { Miniflare, createFetchMock } from "miniflare";
// 创建 `MockAgent` 并将其连接到 `Miniflare` 实例
const fetchMock = createFetchMock();
const mf = new Miniflare({
modules: true,
script: `
export default {
async fetch(request, env, ctx) {
const res = await fetch("https://example.com/thing");
const text = await res.text();
return new Response(\`response:\${text}\`);
}
}
`,
fetchMock,
});
// 当未找到匹配的 Mock 请求时抛出异常
// (参见 https://undici.nodejs.org/#/docs/api/MockAgent?id=mockagentdisablenetconnect)
fetchMock.disableNetConnect();
// Mock 对 https://example.com/thing 的请求
// (参见 https://undici.nodejs.org/#/docs/api/MockAgent?id=mockagentgetorigin)
const origin = fetchMock.get("https://example.com");
// (参见 https://undici.nodejs.org/#/docs/api/MockPool?id=mockpoolinterceptoptions)
origin
.intercept({ method: "GET", path: "/thing" })
.reply(200, "Mocked response!");
const res = await mf.dispatchFetch("http://localhost:8787/");
console.log(await res.text()); // "response:Mocked response!"Miniflare 不支持限制子请求的数量。如果你从 Worker 发出大量子请求,请务必注意这一点。