skip to content

In a Node.js test run where test files share one process, a required cache module leaks entries between files; how do you isolate it, and what does deleting its require.cache entry not reset?

level: seniorimportance: should knowfreq 38%

answer

  1. module-level state lives per process
  2. factory or reset beats eviction
  3. require.resolve gives the cache key
  4. old references survive the delete

basics

~20 s

Move the state out of module scope with a factory, reset function or injected instance, or run files in separate processes. Deleting require.cache[require.resolve(path)] only makes the next require re-run the file; existing holders keep the old object.

solid answer

~40 s

Node runs a CommonJS module once per process, so a module-level `Map` in `cache.js` is shared by every test file loaded into that process. The durable fix is in the module: export a factory such as `createCache()`, or a `reset()` you call in `beforeEach`, or inject the instance. Process isolation also works, and `node --test` runs each file in its own child process by default. Deleting `require.cache[require.resolve('./cache')]` is the blunt option: the next `require` re-executes the file and returns a new object, but modules that already hold the old export keep it, the file's own dependencies stay cached, and the old module stays referenced from its parent's `module.children`. The result is two caches in one process, which is a classic source of flaky tests.

code

javascript · 17 lines
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cjs-'));
const file = path.join(dir, 'store.js');
fs.writeFileSync(file, 'module.exports = new Map();\n');

const first = require(file);
first.set('user', 'alice');

delete require.cache[require.resolve(file)];
const second = require(file);

console.log(first === second);   // false
console.log(second.get('user')); // undefined
console.log(first.get('user'));  // alice

go deeper

for a junior

Recall that a required module is created once per process, so top-level state in it is shared by every test file in that process.

for a middle

Explain how require.resolve produces the cache key and what the next require does after an entry is deleted.

for a senior

Show the production judgment: prefer factories, reset functions or injection, and explain why eviction yields two instances when earlier holders keep the old export.

for a principal

Set a team rule that modules expose their state through explicit constructors or resets, so test isolation does not depend on runner process settings.

## Why the state leaks Node caches every CommonJS module in `require.cache`, keyed by its resolved absolute filename, and runs its top-level code only once per process. A module such as this one therefore holds **one** `Map` for as long as the process lives: ```js // cache.js const entries = new Map(); module.exports = { get: (k) => entries.get(k), set: (k, v) => entries.set(k, v), }; ``` When a test runner loads several test files **into the same process**, the sequence is: 1. `users.test.js` requires `cache.js`; the file runs and the `Map` is created. 2. Its tests call `set('user:1', ...)`. 3. `orders.test.js` requires `cache.js`; Node returns the cached exports without re-running the file. 4. Its tests see `user:1` already present, and pass or fail depending on file order. The bug is **order-dependent**: the suite passes when one file runs alone and fails in the full run, or the other way round. ## Fix the module, not the cache The durable fixes change where state is created: - **Export a factory.** `module.exports = function createCache() { const entries = new Map(); ... }` lets each test, and each production caller that needs separate state, get its own instance. - **Export an explicit reset.** A `clear()` or `reset()` function called from a `beforeEach` hook keeps the singleton but makes its state resettable on purpose. - **Inject the instance.** Code under test receives the cache as an argument instead of requiring a module-level one, so tests pass a fresh instance. These fixes also make production code clearer: whoever owns the state is visible at the call site. ## Isolating by process Separate processes get separate module caches. The built-in runner does this by default: `node --test` uses `--test-isolation=process`, which runs each test file in its own child process, so a module-level `Map` cannot leak from one file to another. Running with `--test-isolation=none`, or with any runner that loads all files into one process, brings the leak back. Process isolation hides the coupling rather than removing it, and it still lets tests **inside one file** share state. ## What deleting a `require.cache` entry actually does The blunt tool is to evict the module so the next `require` executes it again: ```js delete require.cache[require.resolve('./cache')]; const fresh = require('./cache'); ``` `require.resolve` returns the absolute resolved filename, which is the cache key; it throws a `MODULE_NOT_FOUND` error if the module cannot be found. Deleting the entry has a narrow effect: | Effect | Reset? | |---|---| | The next `require('./cache')` re-runs `cache.js` and returns a new object | Yes | | Modules that already required `cache.js` and kept a reference | No, they hold the old object | | Modules that `cache.js` itself required | No, each keeps its own cache entry | | The old `Module` object listed in the requiring parent's `module.children` | No, it stays referenced there | | A native addon (a `.node` file) | No, the docs say reloading one results in an error | The first row is the only thing that changes. If `service.js` required `cache.js` before the eviction and the test requires it after, the process now holds **two caches**: the service writes to the old one and the test reads the new one. This split-brain singleton is the most common way cache-deletion "fixes" turn into flaky tests. Evicting the consumers as well, in the right order, works but is fragile; a factory or reset function is simpler. Repeatedly evicting and re-requiring in a long-running process, for example as a home-made hot reload, also retains memory: the parent's `module.children` array keeps every old `Module` it loaded. ## Recognising the leak The pattern has a recognisable signature in a single-process run: - A test passes when its file runs alone and fails in the full suite, or the reverse. - Failures move when files are renamed or the runner changes its ordering. - Counters, caches or registries start a file with entries that file never wrote. ## A short checklist 1. Find the module-level state: anything created at the top level of a required file. 2. Prefer a factory, a reset function or injection over cache eviction. 3. If you must evict, compute the key with `require.resolve`, evict before anything else requires the module, and require consumers afresh too. 4. Keep test files process-isolated, but do not rely on it to hide shared state inside a file. ES modules loaded with `import` do not use `require.cache` at all; the ES module loader keeps its own separate cache, and none of the eviction above applies to them.

  • In Node.js, why does require.resolve matter when deleting from require.cache?
    `require.cache` is keyed by the absolute resolved filename, not by the specifier you wrote. `require.resolve('./cache')` runs the same resolution `require` would, from the calling file, and returns that key without loading the module. Deleting `require.cache['./cache']` deletes nothing, because no entry has that key.
  • In Node.js, is a test file that passes alone but fails in the full single-process run evidence of a cache leak?
    It is the typical symptom, not proof. Order-dependent results point to shared state, and module-level state reached through `require` is a common source, but environment variables, timers left running, or a shared external resource can cause the same pattern. Running the files in a different order, or with process isolation, helps confirm that module state is the cause.

  • Deleting a require.cache entry resets the module for every file that uses it
  • The cache key is the string passed to require, such as './cache'
  • Deleting the entry also unloads every module the evicted file required
  • Native addons can be reloaded by deleting them from require.cache
  • Clearing require.cache also resets modules loaded with import