๐ธ Web Standards
- Web Standards Reference
- Encoding Reference
- Fetch Reference
- Request Reference
- Response Reference
- Streams Reference
- Web Crypto Reference
When using the API, Miniflare allows you to substitute custom Responses for
fetch() calls using undici's
MockAgent API โ.
This is useful for testing Workers that make HTTP requests to other services. To
enable fetch mocking, create a
MockAgent โ
using the createFetchMock() function, then set this using the fetchMock
option.
import { Miniflare, createFetchMock } from "miniflare";
// Create `MockAgent` and connect it to the `Miniflare` instanceconst 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 does not support limiting the amount of subrequests. Please keep this in mind if you make a large amount of subrequests from your Worker.
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Products
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark