javascript / expert
Snippet
Custom ES Module Hooks for Dynamic Test Double Interception
Node.js ES Module customization hooks allow developers to intercept module resolution (`resolve`) and source code loading (`load`). This pattern enables injecting test double mocks, virtual modules, or dynamic code transformations at runtime.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export async function resolve(specifier, context, nextResolve) {if (specifier.startsWith('mock:')) {const realModule = specifier.slice(5);return {shortCircuit: true,url: `file:///test-mocks/${realModule}.mock.js`};}return nextResolve(specifier, context);}export async function load(url, context, nextLoad) {if (url.includes('/test-mocks/')) {return {format: 'module',shortCircuit: true,source: 'export const status = "mocked"; export default { mocked: true };'};}return nextLoad(url, context);}
nodejs
Breakdown
1
export async function resolve(specifier, context, nextResolve) {
Exports a Node.js module resolution hook to intercept import specifiers before disk evaluation.
2
shortCircuit: true,
Signals to Node.js module loader chain to skip remaining default resolution logic.
3
export async function load(url, context, nextLoad) {
Exports an ES module loading hook to dynamically transform or provide virtual source code string payloads.
4
source: 'export const status = "mocked"; export default { mocked: true };'
Synthesizes in-memory virtual JavaScript code string payloads for stubbed specifiers.