Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Web 標準

最終更新 Markdown で表示Agent セットアップ

アウトバウンドの fetch リクエストをモックする

API を使うとき、Miniflare では undiciMockAgent APIfetch() 呼び出しにカスタムの Response を差し込めます。 ほかのサービスへ HTTP リクエストする Worker のテストに便利です。 fetch のモックを有効にするには、createFetchMock() 関数で MockAgent を作成し、fetchMock オプションで設定します。

import { Miniflare, createFetchMock } from "miniflare";

// Create `MockAgent` and connect it to the `Miniflare` instance
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,
});

// Throw when no matching mocked request is found
// (see https://undici.nodejs.org/#/docs/api/MockAgent?id=mockagentdisablenetconnect)
fetchMock.disableNetConnect();

// Mock request to https://example.com/thing
// (see https://undici.nodejs.org/#/docs/api/MockAgent?id=mockagentgetorigin)
const origin = fetchMock.get("https://example.com");
// (see 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 から大量のサブリクエストを送る場合は、この点に注意してください。

役に立ちましたか?