@@ -7,7 +7,12 @@ import type {
77import { LegacyFakeTimers , ModernFakeTimers } from "@jest/fake-timers" ;
88import type { Circus , Config , Global } from "@jest/types" ;
99import { CachePlugin } from "@miniflare/cache" ;
10- import { BindingsPlugin , CorePlugin , MiniflareCore } from "@miniflare/core" ;
10+ import {
11+ BindingsPlugin ,
12+ CorePlugin ,
13+ MiniflareCore ,
14+ createFetchMock ,
15+ } from "@miniflare/core" ;
1116import {
1217 DurableObjectId ,
1318 DurableObjectStorage ,
@@ -22,13 +27,15 @@ import { SitesPlugin } from "@miniflare/sites";
2227import { WebSocketPlugin } from "@miniflare/web-sockets" ;
2328import { ModuleMocker } from "jest-mock" ;
2429import { installCommonGlobals } from "jest-util" ;
30+ import { MockAgent } from "undici" ;
2531import { StackedMemoryStorageFactory } from "./storage" ;
2632
2733declare global {
2834 function getMiniflareBindings < Bindings = Context > ( ) : Bindings ;
2935 function getMiniflareDurableObjectStorage (
3036 id : DurableObjectId
3137 ) : Promise < DurableObjectStorage > ;
38+ function getMiniflareFetchMock ( ) : MockAgent ;
3239 function flushMiniflareDurableObjectAlarms (
3340 ids : DurableObjectId [ ]
3441 ) : Promise < void > ;
@@ -74,6 +81,7 @@ export default class MiniflareEnvironment implements JestEnvironment<Timer> {
7481
7582 private readonly storageFactory = new StackedMemoryStorageFactory ( ) ;
7683 private readonly scriptRunner : VMScriptRunner ;
84+ private readonly mockAgent : MockAgent ;
7785
7886 constructor (
7987 config :
@@ -94,6 +102,8 @@ export default class MiniflareEnvironment implements JestEnvironment<Timer> {
94102 defineHasInstances ( this . context ) ;
95103 this . scriptRunner = new VMScriptRunner ( this . context ) ;
96104
105+ this . mockAgent = createFetchMock ( ) ;
106+
97107 const global = ( this . global = vm . runInContext ( "this" , this . context ) ) ;
98108 global . global = global ;
99109 global . self = global ;
@@ -205,6 +215,8 @@ export default class MiniflareEnvironment implements JestEnvironment<Timer> {
205215 // context, so we'd be returning the actual time anyway, and this
206216 // might mess with Jest's own mocking.
207217 actualTime : true ,
218+ // - We always want getMiniflareFetchMock() to return this MockAgent
219+ fetchMock : this . mockAgent ,
208220 }
209221 ) ;
210222
@@ -226,6 +238,7 @@ export default class MiniflareEnvironment implements JestEnvironment<Timer> {
226238 const state = await plugin . getObject ( storage , id ) ;
227239 return state . storage ;
228240 } ;
241+ global . getMiniflareFetchMock = ( ) => this . mockAgent ;
229242 global . flushMiniflareDurableObjectAlarms = async (
230243 ids ?: DurableObjectId [ ]
231244 ) : Promise < void > => {
0 commit comments