Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Miniflare 3] Add back support for fetchMock #632

Merged
merged 1 commit into from
Jul 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/miniflare/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,14 @@ parameter in module format Workers.
configured service. Service designators follow the same rules above for
`serviceBindings`.

- `fetchMock?: import("undici").MockAgent`

An [`undici` `MockAgent`](https://undici.nodejs.org/#/docs/api/MockAgent) to
dispatch this Worker's global `fetch()` requests through.

> :warning: `outboundService` and `fetchMock` are mutually exclusive options.
> At most one of them may be specified per Worker.

- `routes?: string[]`

Array of route patterns for this Worker. These follow the same
Expand Down
23 changes: 22 additions & 1 deletion packages/miniflare/src/plugins/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import fs from "fs/promises";
import tls from "tls";
import { TextEncoder } from "util";
import { bold } from "kleur/colors";
import { MockAgent } from "undici";
import SCRIPT_ENTRY from "worker:core/entry";
import { z } from "zod";
import { fetch } from "../../http";
import {
Service,
ServiceDesignator,
Expand Down Expand Up @@ -70,7 +72,11 @@ if (process.env.NODE_EXTRA_CA_CERTS !== undefined) {
const encoder = new TextEncoder();
const numericCompare = new Intl.Collator(undefined, { numeric: true }).compare;

export const CoreOptionsSchema = z.intersection(
export function createFetchMock() {
return new MockAgent();
}

const CoreOptionsSchemaInput = z.intersection(
SourceOptionsSchema,
z.object({
name: z.string().optional(),
Expand All @@ -85,11 +91,26 @@ export const CoreOptionsSchema = z.intersection(
textBlobBindings: z.record(z.string()).optional(),
dataBlobBindings: z.record(z.string()).optional(),
serviceBindings: z.record(ServiceDesignatorSchema).optional(),

outboundService: ServiceDesignatorSchema.optional(),
fetchMock: z.instanceof(MockAgent).optional(),

unsafeEphemeralDurableObjects: z.boolean().optional(),
})
);
export const CoreOptionsSchema = CoreOptionsSchemaInput.transform((value) => {
const fetchMock = value.fetchMock;
if (fetchMock !== undefined) {
if (value.outboundService !== undefined) {
throw new MiniflareCoreError(
"ERR_MULTIPLE_OUTBOUNDS",
"Only one of `outboundService` or `fetchMock` may be specified per worker"
);
}
value.outboundService = (req) => fetch(req, { dispatcher: fetchMock });
}
return value;
});

export const CoreSharedOptionsSchema = z.object({
host: z.string().optional(),
Expand Down
1 change: 1 addition & 0 deletions packages/miniflare/src/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ export {
SERVICE_ENTRY,
CoreOptionsSchema,
CoreSharedOptionsSchema,
createFetchMock,
getGlobalServices,
ModuleRuleTypeSchema,
ModuleRuleSchema,
Expand Down
3 changes: 2 additions & 1 deletion packages/miniflare/src/shared/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export type MiniflareCoreErrorCode =
| "ERR_FUTURE_COMPATIBILITY_DATE" // Compatibility date in the future
| "ERR_NO_WORKERS" // No workers defined
| "ERR_DUPLICATE_NAME" // Multiple workers defined with same name
| "ERR_DIFFERENT_UNIQUE_KEYS"; // Multiple Durable Object bindings declared for same class with different unsafe unique keys
| "ERR_DIFFERENT_UNIQUE_KEYS" // Multiple Durable Object bindings declared for same class with different unsafe unique keys
| "ERR_MULTIPLE_OUTBOUNDS"; // Both `outboundService` and `fetchMock` specified
export class MiniflareCoreError extends MiniflareError<MiniflareCoreErrorCode> {}

export class HttpError extends MiniflareError<number> {
Expand Down
35 changes: 35 additions & 0 deletions packages/miniflare/test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
MiniflareOptions,
Response,
_transformsForContentEncoding,
createFetchMock,
fetch,
} from "miniflare";
import {
Expand Down Expand Up @@ -369,6 +370,40 @@ test("Miniflare: custom outbound service", async (t) => {
});
});

test("Miniflare: fetch mocking", async (t) => {
const fetchMock = createFetchMock();
fetchMock.disableNetConnect();
const origin = fetchMock.get("https://example.com");
origin.intercept({ method: "GET", path: "/" }).reply(200, "Mocked response!");

const mf = new Miniflare({
modules: true,
script: `export default {
async fetch() {
return fetch("https://example.com/");
}
}`,
fetchMock,
});
const res = await mf.dispatchFetch("http://localhost");
t.is(await res.text(), "Mocked response!");

// Check `outboundService`and `fetchMock` mutually exclusive
await t.throwsAsync(
mf.setOptions({
script: "",
fetchMock,
outboundService: "",
}),
{
instanceOf: MiniflareCoreError,
code: "ERR_MULTIPLE_OUTBOUNDS",
message:
"Only one of `outboundService` or `fetchMock` may be specified per worker",
}
);
});

test("Miniflare: custom upstream as origin", async (t) => {
const upstream = await useServer(t, (req, res) => {
res.end(`upstream: ${new URL(req.url ?? "", "http://upstream")}`);
Expand Down