Skip to content

Commit

Permalink
Allow magic proxy to be used from Jest (#683)
Browse files Browse the repository at this point in the history
When running in Jest, `require("undici")` inside a worker thread
fails. Instead, we need to call `createRequire()` first, using the
`__filename` of the worker host. The `require` function returned
from that can then be used to `require("undici")`.
  • Loading branch information
mrbbot committed Oct 31, 2023
1 parent c817ba7 commit e7136d9
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions packages/miniflare/src/plugins/core/proxy/fetch-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,17 @@ type WorkerResponse = { id: number } & (
);

const WORKER_SCRIPT = /* javascript */ `
const { createRequire } = require("module");
const { workerData } = require("worker_threads");
const { Client, fetch } = require("undici");
// Not using parentPort here so we can call receiveMessageOnPort() in host
const { notifyHandle, port } = workerData;
const { notifyHandle, port, filename } = workerData;
// When running Miniflare from Jest, regular 'require("undici")' will fail here
// with "Error: Cannot find module 'undici'". Instead we need to create a
// 'require' using the '__filename' of the host... :(
const actualRequire = createRequire(filename);
const { Client, fetch } = actualRequire("undici");
let clientUrl;
let client;
Expand Down Expand Up @@ -103,6 +109,7 @@ export class SynchronousFetcher {
workerData: {
notifyHandle: this.#notifyHandle,
port: this.#channel.port2,
filename: __filename,
},
transferList: [this.#channel.port2],
});
Expand Down

0 comments on commit e7136d9

Please sign in to comment.