Skip to content

Commit f44db76

Browse files
committed
Refactor: add getTestDispatcher and update tests to use initializeTestDispatcher
- Added getTestDispatcher function to obtain a MockAgent from undici. - Refactored test code to use a new helper function initializeTestDispatcher, which sets up the test dispatcher and returns an interceptor. - Renamed mockPool to interceptor in the test file for clarity.
1 parent 227128d commit f44db76

File tree

3 files changed

+91
-96
lines changed

3 files changed

+91
-96
lines changed

v-next/hardhat-utils/src/request.ts

+13
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ export const DEFAULT_POOL_MAX_CONNECTIONS = 128;
3030
export const DEFAULT_USER_AGENT = "Hardhat";
3131

3232
export type Dispatcher = UndiciT.Dispatcher;
33+
export type TestDispatcher = UndiciT.MockAgent;
34+
export type Interceptable = UndiciT.Interceptable;
3335

3436
/**
3537
* Options to configure the dispatcher.
@@ -319,6 +321,17 @@ export async function getDispatcher(
319321
}
320322
}
321323

324+
export async function getTestDispatcher(
325+
options: {
326+
timeout?: number;
327+
} = {},
328+
): Promise<TestDispatcher> {
329+
const { MockAgent } = await import("undici");
330+
331+
const baseOptions = getBaseDispatcherOptions(options.timeout, true);
332+
return new MockAgent(baseOptions);
333+
}
334+
322335
/**
323336
* Determines whether a proxy should be used for a given url.
324337
*
+13-16
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,29 @@
1-
import type { DispatcherOptions } from "../../src/request.js";
2-
import type { Interceptable } from "undici";
1+
import type { Interceptable } from "../../src/request.js";
32

43
import { after, before } from "node:test";
54

6-
import { MockAgent } from "undici";
5+
import { getTestDispatcher } from "../../src/request.js";
76

8-
export function getTestDispatcherOptions(
9-
options: DispatcherOptions = {},
10-
): DispatcherOptions & { isTestDispatcher: true } {
11-
return {
12-
...options,
13-
isTestDispatcher: true,
14-
};
7+
interface InitializeOptions {
8+
url?: string;
9+
timeout?: number;
1510
}
1611

17-
const mockAgent = new MockAgent({
18-
keepAliveTimeout: 10,
19-
keepAliveMaxTimeout: 10,
20-
});
12+
export const initializeTestDispatcher = async (
13+
options: InitializeOptions = {},
14+
): Promise<Interceptable> => {
15+
const { url = "http://localhost", timeout } = options;
2116

22-
export const mockPool: Interceptable = mockAgent.get("http://localhost:3000");
17+
const mockAgent = await getTestDispatcher({ timeout });
18+
const interceptor = mockAgent.get(url);
2319

24-
export const setupRequestMocking: () => void = () => {
2520
before(() => {
2621
mockAgent.disableNetConnect();
2722
});
2823

2924
after(() => {
3025
mockAgent.enableNetConnect();
3126
});
27+
28+
return interceptor;
3229
};

0 commit comments

Comments
 (0)