Jest 25 ๐ Performance โ unrs-resolver, barrel file elimination, and open handle detection
Jest’s startup has always paid a tax that other test runners avoid: every test file, every import, and every dependency has to be resolved through a custom resolver layer that sits between Node and the module system. Jest 30 replaced the decades-old resolve package with unrs-resolver, a Rust-native resolver that mirrors what oxc-resolver does for the Oxc toolchain. The change is not cosmetic โ resolution is one of the hottest paths in Jest’s module loading pipeline, and swapping a JavaScript resolver for a native one removes a measurable slice off cold starts and watch-mode re-runs. This chapter covers that swap, the barrel-file elimination strategy that removes the largest remaining resolution bottleneck, and the open handle detection that catches the asynchronous leaks which make Jest hang at exit.
The sections that follow walk through how unrs-resolver changes resolution, what barrel files are and why they are expensive to resolve, how Jest’s open handle detection reports the handles that keep the process alive, and the configuration knobs that connect the three. The thread running through all of it is that Jest’s performance is dominated by the module graph, and every optimization here is about making that graph smaller or faster to walk.
Key point: Jest 30’s unrs-resolver makes module resolution native and dramatically faster, but the biggest remaining win is eliminating barrel files, because a single index.ts re-export can force Jest to parse and evaluate every file in a directory; open handle detection then catches the async leaks that barrel-file elimination can accidentally expose.
Why Jest performance work exists
The resolver tax problem. Every import statement in every test file passes through Jest’s resolver before Node sees it. The legacy resolve package was pure JavaScript, and it did the same synchronous filesystem probes for every specifier: check the exact path, then the extensions, then the directory index, then node_modules. On a project with thousands of imports, the resolver alone accounted for a significant portion of the time between jest being invoked and the first test executing. The unrs-resolver swap is the direct response to that: a native resolver does the same probes in a fraction of the time.
The barrel file problem. A barrel file is an index.ts that re-exports everything from a directory: export * from "./button", export * from "./input", and so on. The pattern is convenient for consumers โ import { Button } from "./components" โ but it is hostile to module loaders. When Jest resolves ./components, it loads the barrel, which loads every re-exported module, which loads their dependencies. A single test that imports one component from a barrel pulls the entire directory into the module graph. The cost is not in resolution per se, but in the transitive evaluation that resolution triggers.
The open handle problem. Jest cannot exit until the Node event loop drains. A test that starts a setInterval, opens a database connection, or leaves a promise pending will keep the process alive after the last test finishes, and Jest hangs. The open handle detection feature exists because that hang is one of the most common and most confusing Jest failures โ the tests pass, but the process never exits. The detection reports which handle is keeping the loop alive, and the report is the diagnostic that turns a silent hang into an actionable message.
The watch mode problem. In watch mode, Jest re-runs only the tests affected by a changed file. The affected-tests calculation depends on the dependency graph, and barrel files make that graph enormous: a change to any file in a directory invalidates the barrel, which invalidates every test that imports from it. Barrel file elimination is as much a watch-mode optimization as a cold-start one.
The trade-off. Eliminating barrel files makes imports explicit and longer, and it requires discipline across a codebase. The native resolver removes a JavaScript layer that some projects relied on for custom resolution behavior. Open handle detection adds a small amount of overhead to teardown, and it produces false positives for handles that are legitimately long-lived. Each optimization is a deliberate trade, and the sections below cover what each one buys and what it costs.
a. The unrs-resolver swap
Jest 30 replaced the resolve package with unrs-resolver, a native resolver exposed to JavaScript through a Node-API binding. The resolver implements the same resolution algorithm โ relative paths, extension probing, directory index files, node_modules walking, and package.json exports/imports maps โ but it does the filesystem work in Rust rather than JavaScript. The change is transparent to test code: imports resolve the same way, and the only observable difference is speed.
The resolver is configured through the same moduleNameMapper, moduleDirectories, moduleFileExtensions, and resolver options that Jest has always had. The unrs-resolver is the default engine underneath them, and a custom resolver path still overrides it when a project needs bespoke behavior.
// jest.config.js
module.exports = {
// The native resolver is the default; these options feed it
moduleDirectories: ["node_modules", "src"], // where to look for bare specifiers
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json"], // extension probe order
moduleNameMapper: {
"^@app/(.*)$": "<rootDir>/src/$1", // alias mapping resolved natively
},
};
The resolver’s speed comes from doing the probe sequence in native code. For a specifier like @app/components/button, Jest first applies the moduleNameMapper to rewrite it to <rootDir>/src/components/button, then the resolver probes the extensions in moduleFileExtensions order, then checks for a directory index file. Each of those steps is a filesystem call, and the native resolver batches and caches them in a way the JavaScript resolver could not.
The resolver option remains the escape hatch. A project with a custom resolution scheme โ a monorepo with workspace-relative aliases, a project that resolves .vue files, a project that needs conditional exports โ points the option at a custom resolver module, and that module runs in JavaScript on top of the native base.
// jest.config.js โ custom resolver override
module.exports = {
resolver: "<rootDir>/tools/custom-resolver.js",
};
// tools/custom-resolver.js โ runs for every specifier Jest resolves
module.exports = (request, options) => {
// Delegate to the default native resolver for most specifiers
if (!request.startsWith("virtual:")) {
return options.defaultResolver(request, options);
}
// Handle the project-specific virtual module scheme
return `${options.rootDir}/virtual/${request.slice("virtual:".length)}.js`;
};
The custom resolver is the slow path โ it runs in JavaScript for every specifier it handles โ so the recommendation is to keep it narrow. A resolver that delegates to options.defaultResolver for everything except a small set of virtual specifiers pays the native cost for the common case and the JavaScript cost only for the exceptions.
b. Barrel file elimination
A barrel file is an index module that re-exports from sibling modules. The pattern is everywhere in component libraries and feature folders:
// src/components/index.ts โ the barrel
export * from "./button";
export * from "./input";
export * from "./select";
export * from "./modal";
export * from "./table";
// ... and forty more
A consumer imports from the barrel: import { Button } from "./components". When Jest resolves that import, it loads src/components/index.ts, which re-exports from every sibling, which means Jest parses and evaluates every sibling and their transitive dependencies. A test that needs Button pays for Modal, Table, and the other forty modules.
The cost shows up in three places. First, the module graph Jest builds at startup is larger, so the first test run is slower. Second, in watch mode, a change to any sibling invalidates the barrel, and every test that imports from the barrel is re-run. Third, the memory footprint of the test worker grows with the graph, and large graphs trigger more garbage collection.
The fix is to import from the specific module rather than the barrel:
// before โ pulls the whole directory into the graph
import { Button } from "./components";
// after โ pulls only the button module
import { Button } from "./components/button";
The change is mechanical, and it is best enforced by a lint rule rather than by convention. The no-restricted-imports ESLint rule with a pattern matching directory imports catches new barrel imports before they land.
// .eslintrc.js โ forbid imports that resolve to a directory barrel
module.exports = {
rules: {
"no-restricted-imports": [
"error",
{
patterns: [
{
group: ["*/components", "*/components/index"],
message: "Import from the specific module, not the barrel.",
},
],
},
],
},
};
The trade-off is real: barrel files exist because they make imports shorter and hide the internal structure of a directory. Eliminating them makes imports longer and couples consumers to file paths. The compromise many projects adopt is to keep barrels for public API surfaces โ the package entry point โ and eliminate them inside the codebase, so a test imports @app/components/button rather than @app/components. The package.json exports map then defines the public surface, and the internal graph stays flat.
Jest’s moduleNameMapper can also be used to point a barrel import directly at the specific module during tests, but that is a workaround, not a fix โ it hides the barrel rather than removing it, and it diverges test resolution from production resolution.
c. Open handle detection
Jest cannot exit until the Node event loop is empty. A test that starts a setInterval, opens a database connection, creates a server, or leaves a promise pending keeps the loop alive, and Jest hangs after the last test with no output explaining why. Open handle detection is the feature that reports the handle.
The detection is on by default in recent Jest versions. When Jest detects that the process has not exited within a timeout after the last test, it inspects the active handles and prints a report naming the handle type and the test that created it, where the information is available.
// A test that leaks an interval โ Jest will not exit
test("starts a poller", () => {
// This interval is never cleared, so the event loop never drains
setInterval(() => {
poll();
}, 1000);
});
The report names the handle โ setInterval, in this case โ and points at the test that created it. The fix is to clear the handle in the test or in an afterEach:
// The fixed test โ the interval is cleared when the test ends
test("starts a poller", () => {
const id = setInterval(() => {
poll();
}, 1000);
// Clean up the handle so the event loop can drain
afterEach(() => clearInterval(id));
});
The detectOpenHandles option is the explicit form. It is slower โ it runs the full handle inspection after every test file โ so it is normally enabled only when debugging a hang, not in the regular configuration.
// jest.config.js โ enable the detection when debugging a hang
module.exports = {
detectOpenHandles: true, // slower; turn on only while investigating
};
The detection interacts with barrel file elimination in a subtle way. A barrel file pulls in modules that may open handles at import time โ a database client that connects on import, a metrics library that starts a reporter. When the barrel is eliminated, those modules are no longer loaded, and the handle leak disappears along with them. The reverse is also true: a test that passes in isolation but hangs in the full suite is often loading a barrel that transitively imports a module with an unclosed handle.
Complete Example Session
// ============================================
// PART 1: THE CONFIG WITH THE NATIVE RESOLVER
// ============================================
// jest.config.js
module.exports = {
// The unrs-resolver is the default; these options feed it
moduleDirectories: ["node_modules", "src"],
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json"],
};
// ============================================
// PART 2: THE MODULE NAME MAPPER
// ============================================
// jest.config.js โ aliases are resolved natively
module.exports = {
moduleNameMapper: {
"^@app/(.*)$": "<rootDir>/src/$1",
},
};
// ============================================
// PART 3: THE BARREL FILE (BEFORE)
// ============================================
// src/components/index.ts โ every sibling is pulled in
export * from "./button";
export * from "./input";
export * from "./select";
export * from "./modal";
// ============================================
// PART 4: THE SPECIFIC IMPORT (AFTER)
// ============================================
// The test imports the specific module, not the barrel
import { Button } from "./components/button";
// ============================================
// PART 5: THE LINT GUARD
// ============================================
// .eslintrc.js โ forbid new barrel imports
module.exports = {
rules: {
"no-restricted-imports": [
"error",
{ patterns: [{ group: ["*/components"], message: "Import the specific module." }] },
],
},
};
// ============================================
// PART 6: THE LEAKING TEST
// ============================================
test("starts a poller", () => {
// The interval is never cleared โ Jest will hang
setInterval(() => poll(), 1000);
});
// ============================================
// PART 7: THE FIXED TEST
// ============================================
test("starts a poller", () => {
const id = setInterval(() => poll(), 1000);
// Clear the handle so the event loop drains
afterEach(() => clearInterval(id));
});
// ============================================
// PART 8: THE DETECTION CONFIG
// ============================================
// jest.config.js โ enable while debugging a hang
module.exports = {
detectOpenHandles: true, // slower; disable after the fix
};
// ============================================
// PART 9: THE CUSTOM RESOLVER
// ============================================
// tools/custom-resolver.js โ delegates to the native base
module.exports = (request, options) => {
if (!request.startsWith("virtual:")) {
return options.defaultResolver(request, options); // native fast path
}
return `${options.rootDir}/virtual/${request.slice(8)}.js`;
};
// ============================================
// PART 10: THE MEASUREMENT
// ============================================
// Run before and after the barrel removal to see the graph shrink
// npx jest --showSeed --listTests
// npx jest --runInBand --detectOpenHandles
The ten parts covered the native resolver config, the alias mapping, the barrel before and the specific import after, the lint guard that enforces the change, the leaking test and its fix, the detection config, the custom resolver escape hatch, and the measurement commands that confirm the graph shrank.
Quick Reference
Resolver Options
| Option | Effect |
|---|---|
moduleDirectories | Where bare specifiers are looked up |
moduleFileExtensions | Extension probe order |
moduleNameMapper | Alias rewrites before resolution |
resolver | Custom resolver override |
Barrel File Costs
| Cost | Cause |
|---|---|
| Cold start | Whole directory parsed on first import |
| Watch re-runs | Any sibling change invalidates the barrel |
| Memory | Graph grows with every re-export |
| Handle leaks | Transitive modules open handles at import |
Open Handle Options
| Option | Effect |
|---|---|
detectOpenHandles | Report handles after each file (slow) |
| Default detection | Reports handles when exit is delayed |
afterEach cleanup | Clears the handle per test |
--runInBand | Single process; easier handle attribution |
Best Practices
โ Do This:
// Let the native resolver do the work
moduleDirectories: ["node_modules", "src"]; // โ
// Import the specific module
import { Button } from "./components/button"; // โ
// Enforce the rule with lint
"no-restricted-imports": ["error", { patterns: [...] }]; // โ
// Clear handles in the test
afterEach(() => clearInterval(id)); // โ
// Enable detection only while debugging
detectOpenHandles: true; // โ
โ Don’t Do This:
// Import through the barrel
import { Button } from "./components"; // โ
// Leave an interval running
setInterval(() => poll(), 1000); // โ
// Keep detection on in CI
detectOpenHandles: true; // slower on every run // โ
// Write a resolver that reimplements the default
module.exports = (req, opts) => mySlowResolve(req); // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Jest hangs after tests | Unclosed handle keeps the loop alive | clearInterval, close connections |
| No speed gain from resolver | Custom resolver reimplements default | Delegate to options.defaultResolver |
| Watch re-runs everything | Barrel file invalidates all importers | Import specific modules |
| Handle report points at import | Barrel transitively opens a handle | Eliminate the barrel |
| Detection slows CI | detectOpenHandles runs every file | Enable only when debugging |
Real-World Examples
1. Native resolver config
moduleDirectories: ["node_modules", "src"];
2. Alias mapping
moduleNameMapper: { "^@app/(.*)$": "<rootDir>/src/$1" };
3. Barrel file
export * from "./button";
export * from "./input";
4. Specific import
import { Button } from "./components/button";
5. Lint guard
"no-restricted-imports": ["error", { patterns: [{ group: ["*/components"] }] }];
6. Leaking interval
setInterval(() => poll(), 1000);
7. Clear the handle
afterEach(() => clearInterval(id));
8. Detection config
detectOpenHandles: true;
9. Custom resolver
module.exports = (req, opts) => opts.defaultResolver(req, opts);
10. Measurement
npx jest --runInBand --detectOpenHandles;
Visual
The Resolution Path
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ import { Button } from "./components/button" โ
โ โ
โ Jest resolver โ
โ โ โ
โ โโโ moduleNameMapper rewrite โ
โ โ โ
โ โโโ unrs-resolver (native) โ
โ โ โโโ probe exact path โ
โ โ โโโ probe extensions โ
โ โ โโโ check directory index โ
โ โ โ
โ โผ โ
โ resolved absolute path โโโบ Node module loader โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Barrel File Cost
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ import { Button } from "./components" โ
โ โ
โ components/index.ts โ
โ โโโ ./button โโโ the only one needed โ
โ โโโ ./input โโโ loaded anyway โ
โ โโโ ./select โโโ loaded anyway โ
โ โโโ ./modal โโโ loaded anyway โ
โ โโโ ./table โโโ loaded anyway โ
โ โ
โ Result: the whole directory in the module graph โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Open Handle Hang
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Last test finishes โ
โ โ โ
โ โผ โ
โ Event loop has an active handle? โ
โ โโโ no โโโบ process exits normally โ
โ โโโ yes โโโบ Jest hangs โ
โ โ โ
โ โผ โ
โ detectOpenHandles report โ
โ names the handle and the test โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Three Optimizations
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ OPTIMIZATION WHAT IT REMOVES WHERE โ
โ โ
โ unrs-resolver JS resolver layer startup โ
โ barrel removal transitive modules graph size โ
โ handle detection async leaks teardown โ
โ โ
โ Together: smaller graph, faster resolve, clean exit โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Native resolver | unrs-resolver (default in Jest 30) |
| Resolver override | resolver option |
| Alias mapping | moduleNameMapper |
| Barrel file | index re-exporting siblings |
| Barrel fix | Import the specific module |
| Lint guard | no-restricted-imports |
| Handle detection | detectOpenHandles |
| Handle fix | Clear the handle in afterEach |
Key takeaways:
unrs-resolveris the native resolver. Jest 30 swapped the JavaScriptresolvepackage for a Rust-native resolver, and the samemoduleNameMapperandmoduleDirectoriesoptions now feed it. The change is transparent to test code and faster on every import.- Barrel files are the biggest remaining cost. An
index.tsthat re-exports a directory forces Jest to load every sibling when a test imports one symbol. Importing the specific module removes the transitive evaluation, shrinks the graph, and speeds up watch-mode re-runs. - The lint rule enforces the fix.
no-restricted-importswith a directory pattern catches new barrel imports before they land, so the graph does not regrow. - Open handle detection turns a hang into a message. A leaked interval, connection, or pending promise keeps the event loop alive; the detection names the handle and the test, and the fix is to clear it in the test or in
afterEach. - Detection is a debugging tool, not a CI default.
detectOpenHandlesruns the full handle inspection after each file, which is slow; enable it while investigating a hang and disable it once the leak is fixed.
Remember: Jest’s performance is the module graph’s performance. The native resolver makes every resolution cheaper, barrel file elimination makes the graph smaller, and open handle detection keeps the process from hanging on the async leaks that a large graph hides. Apply all three: keep the resolver native, import specific modules instead of barrels, and clear every handle the tests open.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!