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() が呼ばれている場合は、代わりに指定した upstream からレスポンスを取得します。
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