每当发起 HTTP 请求时,Request 对象会被分发到你的 Worker,然后返回生成的 Response。
Request 对象将包含
cf 对象。
Miniflare 会记录方法、路径、状态码以及响应耗时。
如果 Worker 在生成响应时抛出错误,将返回包含堆栈跟踪的错误页面。
使用 API 时,可以使用 dispatchFetch 函数向 Worker 分发 fetch
事件。这可用于测试响应。dispatchFetch
的 API 与常规 fetch 方法相同:它接受 Request
对象,或 URL 和可选的 RequestInit 对象:
import { Miniflare, Request } from "miniflare";
const mf = new Miniflare({
modules: true,
script: `
export default {
async fetch(request, env, ctx) {
const body = JSON.stringify({
url: event.request.url,
header: event.request.headers.get("X-Message"),
});
return new Response(body, {
headers: { "Content-Type": "application/json" },
});
})
}
`,
});
let res = await mf.dispatchFetch("http://localhost:8787/");
console.log(await res.json()); // { url: "http://localhost:8787/", header: null }
res = await mf.dispatchFetch("http://localhost:8787/1", {
headers: { "X-Message": "1" },
});
console.log(await res.json()); // { url: "http://localhost:8787/1", header: "1" }
res = await mf.dispatchFetch(
new Request("http://localhost:8787/2", {
headers: { "X-Message": "2" },
}),
);
console.log(await res.json()); // { url: "http://localhost:8787/2", header: "2" }分发事件时,你需要自行添加
CF-* 标头 和
cf 对象。
这让你可以控制它们的值以进行测试:
const res = await mf.dispatchFetch("http://localhost:8787", {
headers: {
"CF-IPCountry": "GB",
},
cf: {
country: "GB",
},
});Miniflare 会调用每个 fetch 监听器,直到返回响应。如果没有
返回响应,或抛出了异常且已调用 passThroughOnException(),
响应将从指定的上游获取:
import { Miniflare } from "miniflare";
const mf = new Miniflare({
script: `
addEventListener("fetch", (event) => {
event.passThroughOnException();
throw new Error();
});
`,
upstream: "https://miniflare.dev",
});
// If you don't use the same upstream URL when dispatching, Miniflare will
// rewrite it to match the upstream
const res = await mf.dispatchFetch("https://miniflare.dev/core/fetch");
console.log(await res.text()); // Source code of this page