← Cloudflare Workers / workers / testing / miniflare / core
Webové standardy
- Reference k webovým standardům
- Referenční příručka Encoding
- Referenční informace o Fetch API
- Referenční informace o Request
- Referenční informace o Response
- Reference Streams
- Reference k Web Crypto
Mockování odchozích fetch Požadavky
Při použití API vám Miniflare umožňuje nahradit vlastní Responses pro
fetch() volání pomocí undici's
MockAgent API ↗.
To se hodí při testování Workerů, které odesílají HTTP požadavky na jiné služby. Pro povolení fetch mockování vytvořte
MockAgent ↗
pomocí createFetchMock() funkci a poté ji nastavte pomocí fetchMock
možnost.
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!"Podpožadavky
Miniflare nepodporuje omezení množství dílčí požadavky. Mějte to na paměti, pokud z vašeho Workeru odesíláte velké množství subrequestů.