javascript / expert
Snippet
Dynamic Module Cache Injection for Isolation Testing in Node.js
Node.js uses require.cache to store resolved CommonJS modules. In testing environments without heavy third-party mocking libraries, manipulating this cache allows developers to inject stubs directly into the resolution graph. Returning a cleanup restoration handle prevents test state leakage across execution runs.
snippet.js
javascript
1
2
3
4
5
6
function injectMockModule(modulePath, mockExports) {const resolvedPath = require.resolve(modulePath);const mockModule = { exports: mockExports, loaded: true, id: resolvedPath };require.cache[resolvedPath] = mockModule;return () => { delete require.cache[resolvedPath]; };}
nodejs
Breakdown
1
const resolvedPath = require.resolve(modulePath);
Resolves the absolute file system path of the targeted module to key into require.cache.
2
require.cache[resolvedPath] = mockModule;
Overrides the cached module entry with a custom synthetic module object.
3
return () => { delete require.cache[resolvedPath]; };
Returns a cleanup teardown callback to clear the injected mock after testing completes.