Jest 17 ๐ ESM Support โ Native ESM, import.meta, and file URL handling
Running modern JavaScript and TypeScript test suites under native ECMAScript Modules (ESM) changes how Jest loads files, resolves module specifiers, mocks dependencies, and exposes module metadata. Historically, Jest relied on synchronous CommonJS wrappers and Babel transformations that silently converted import and export statements into require() calls before execution. While convenient, that compilation step breaks down when testing modern packages published strictly as ESM or when application code depends directly on browser-aligned module semantics.
Enabling native ESM support in Jest shifts module resolution onto Node.js’s built-in VM module linker. Instead of intercepting require() calls synchronously, Jest delegates module graph construction and evaluation to Node’s asynchronous ESM loader pipeline. This change enforces strict file extensions on relative imports, disables automatic CommonJS globals like __dirname and __filename, and prevents standard jest.mock() calls from hoisting above static import declarations.
In this chapter, you will learn how to activate Jest’s native ESM runtime using Node’s VM modules flag, convert import.meta.url file URLs into standard filesystem paths, and mock dependencies asynchronously using jest.unstable_mockModule(). We will cover runtime configuration, path resolution utilities, dynamic mocking patterns, and a complete ten-part test session.
Key point: Native ESM support in Jest requires running Node with --experimental-vm-modules, which disables automatic jest.mock() hoisting and replaces synchronous CommonJS globals with import.meta.url and asynchronous dynamic import() workflows.
Why Native ESM Support Exists
The CommonJS emulation problem.
Traditional Jest execution wraps every test and source file in a simulated CommonJS function wrapper using Node’s vm.runInContext API, injecting require, exports, and module variables at runtime. When developers write ES module syntax, a transformer like babel-jest or ts-jest rewrites those statements into CommonJS equivalents before Jest ever sees them. This emulation hides subtle circular dependency bugs, alters live binding semantics, and fails completely when importing third-party packages that ship exclusively with an "exports" map targeting ESM consumers.
The import.meta context problem.
In native ECMAScript Modules, import.meta is a host-created metadata object exposed directly by the JavaScript engine rather than a variable passed into a module wrapper. CommonJS transformers cannot natively represent import.meta.url without resorting to fragile AST hacks or brittle polyfills that inject fake paths. Native ESM execution allows the V8 engine to populate import.meta.url with the authentic file:// URL of the executing module.
The asynchronous evaluation problem.
CommonJS module loading is strictly synchronous, allowing Jest to intercept require() calls on the fly and swap out module exports mid-execution. Native ESM evaluation is inherently asynchronous because the specification supports top-level await across the entire dependency graph. Jest needed a dedicated VM module architecture capable of linking, instantiating, and evaluating module graphs asynchronously before test assertions begin executing.
The dual-package hazard.
When a test runner loads a library via CommonJS require() while application code or transitive dependencies load the exact same library via native import(), Node.js instantiates two separate copies of the package in memory. This split breaks instanceof checks, duplicates singleton state, and causes database connection pools or state managers to misbehave during integration tests. Native ESM mode ensures Jest and Node share a single unified module registry.
The explicit specifier alignment.
Browsers and Node.js native ESM loaders reject extensionless relative imports like ./utils and directory index shortcuts like ./components. Emulating ESM through CommonJS masks missing .js extensions during testing, allowing broken code to pass CI pipelines only to crash in production runtimes. Running Jest in native ESM mode enforces standard URL-based specifier resolution during test execution.
The global scope isolation trade-off.
In CommonJS mode, Jest injects global variables (describe, test, expect, jest) directly into the sandboxed context of every test file. Under native ESM, module scopes are strictly isolated according to the ECMAScript specification, requiring explicit imports from @jest/globals to access mocking utilities and matchers cleanly without relying on implicit global mutation.
a. Activating Native ESM and Node VM Modules
To run Jest without transforming ES modules into CommonJS, you must instruct Node.js to expose its internal vm.SourceTextModule and vm.SyntheticModule APIs. Because these APIs remain flagged in Node.js, Jest cannot enable them automatically from inside a configuration file; the flag must be passed directly to the Node binary before Jest initializes.
JSON
{
"name": "native-esm-service",
"version": "1.0.0",
"type": "module",
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"test:watch": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"jest": "^29.7.0"
}
}
Setting "type": "module" in package.json tells both Node.js and Jest to treat every .js file in the project as a native ES module. Invoking node --experimental-vm-modules node_modules/jest/bin/jest.js directly avoids shell wrapper overhead and ensures the Node process spawns with VM module linking enabled across all worker threads.
When working with TypeScript or custom file extensions, Jest also requires explicit configuration in jest.config.mjs to disable default CommonJS transforms and map TypeScript’s .js import specifiers back to .ts source files on disk.
JavaScript
// jest.config.mjs
export default {
// Use the Node test environment rather than jsdom for backend ESM services
testEnvironment: 'node',
// Disable default babel-jest CommonJS transformations
transform: {},
// Instruct Jest to treat .ts files as native ES modules
extensionsToTreatAsEsm: ['.ts'],
// Strip .js extensions from relative imports so Jest resolves .ts source files
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
};
In this configuration, setting transform: {} prevents Jest from running default Babel transformations that would rewrite import statements back into require() calls. The moduleNameMapper regular expression captures relative paths ending in .js (such as ./parser.js) and maps them to extensionless paths (./parser), allowing Jest to locate ./parser.ts while preserving valid TypeScript NodeNext module resolution.
b. Handling import.meta and File URL Transformations
Native ES modules omit the CommonJS require, __filename, and __dirname wrapper variables. Instead, JavaScript provides import.meta.url, which evaluates to an RFC-compliant file:// URL string pointing to the exact location of the currently executing module on disk (for example, file:///home/user/project/src/loader.js). Passing a file:// URL directly to Node’s fs.readFileSync() or path.resolve() will fail or produce malformed paths on Linux, macOS, and Windows unless properly converted.
JavaScript
// src/config-loader.js
import { readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
// Convert the module's file:// URL into a platform-specific filesystem path
const currentFilePath = fileURLToPath(import.meta.url);
// Extract the directory path equivalent to CommonJS __dirname
const currentDirPath = dirname(currentFilePath);
export async function loadSchemaFile(filename) {
// Safely join the resolved directory with the target fixture or schema file
const targetPath = join(currentDirPath, 'schemas', filename);
const rawContent = await readFile(targetPath, 'utf8');
return JSON.parse(rawContent);
}
The fileURLToPath() function from node:url decodes percent-encoded characters (such as %20 for spaces) and strips the file:// scheme properly across operating systems. Wrapping that output in dirname() from node:path produces a clean, reliable directory path that behaves identically to CommonJS __dirname.
When a module must load legacy CommonJS JSON assets or native .node addons inside an ESM test suite, createRequire() from node:module bridges the gap using import.meta.url as its resolution anchor.
JavaScript
// src/legacy-bridge.js
import { createRequire } from 'node:module';
// Construct a scoped CommonJS require function anchored to this module's URL
const require = createRequire(import.meta.url);
export function readPackageMetadata() {
// Load JSON synchronously without needing experimental import attributes
const pkg = require('../package.json');
return {
name: pkg.name,
version: pkg.version,
};
}
Because createRequire(import.meta.url) binds a standard CommonJS resolver to the current file’s URL, require('../package.json') resolves relative to src/legacy-bridge.js rather than the process’s current working directory (process.cwd()). This guarantees deterministic file loading regardless of which directory you invoke Jest from.
c. Asynchronous Mocking with unstable_mockModule
In CommonJS tests, Jest’s Babel plugin automatically hoists jest.mock('./db.js') calls to the very top of the file before any require() statements execute. Under native ESM, static import declarations are parsed, linked, and evaluated by Node’s module loader before the first line of test code ever executes. As a result, a standard jest.mock() call runs too lateโthe real module has already been loaded and bound into memory.
To mock dependencies in native ESM, you must import jest from @jest/globals, register the mock factory using jest.unstable_mockModule(), and then load the module under test using a dynamic await import() expression.
JavaScript
// tests/user-service.test.js
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
// 1. Define mock functions before registering the module factory
const mockFindUserById = jest.fn();
const mockWriteAuditLog = jest.fn();
// 2. Register the ESM mock asynchronously prior to importing consumers
jest.unstable_mockModule('../src/database.js', () => ({
findUserById: mockFindUserById,
writeAuditLog: mockWriteAuditLog,
}));
// 3. Dynamically import the module under test AFTER the mock is registered
const { deactivateUserAccount } = await import('../src/user-service.js');
describe('deactivateUserAccount', () => {
beforeEach(() => {
// Reset call history and return values between tests
jest.clearAllMocks();
});
it('deactivates an active user and records an audit entry', async () => {
// Arrange mock return values
mockFindUserById.mockResolvedValue({ id: 'usr_42', active: true });
mockWriteAuditLog.mockResolvedValue(true);
// Act using the dynamically imported function
const result = await deactivateUserAccount('usr_42');
// Assert behavior and mock interactions
expect(result).toEqual({ id: 'usr_42', active: false });
expect(mockFindUserById).toHaveBeenCalledWith('usr_42');
expect(mockWriteAuditLog).toHaveBeenCalledWith('DEACTIVATE', 'usr_42');
});
});
Notice the strict ordering enforced by top-level await in this test file. jest.unstable_mockModule() registers the virtual module factory in Jest’s ESM linker registry, and the subsequent await import('../src/user-service.js') forces Node to resolve ../src/database.js against that newly registered mock factory. If user-service.js had been imported via a static top-level import statement, the real database.js module would have been linked first and the mock would have been silently ignored.
When mocking modules that provide both named exports and a default export, your factory function must explicitly include a default key alongside named properties to satisfy ESM named-export validation.
JavaScript
// tests/mailer.test.js
import { describe, expect, it, jest } from '@jest/globals';
// Mock a module that exposes both a default export and named helpers
jest.unstable_mockModule('../src/smtp-transport.js', () => ({
__esModule: true,
default: {
sendMail: jest.fn().mockResolvedValue({ messageId: 'msg_101' }),
},
validateAddress: jest.fn().mockReturnValue(true),
}));
const { dispatchWelcomeEmail } = await import('../src/mailer.js');
describe('dispatchWelcomeEmail', () => {
it('sends an email through the mocked default transport', async () => {
const response = await dispatchWelcomeEmail('dev@example.com');
expect(response.messageId).toBe('msg_101');
});
});
Including default inside the returned object mirrors how Node’s SyntheticModule links ESM exports. Omitting default when the consuming code writes import transport from './smtp-transport.js' will throw a SyntaxError: The requested module './smtp-transport.js' does not provide an export named 'default' during module linking.
Complete Example Session
JavaScript
// ============================================
// PART 1: PACKAGE.JSON ESM CONFIGURATION
// ============================================
// Configure package.json to enforce native ESM resolution and pass the VM flag
const packageManifest = {
name: 'esm-inventory-service',
type: 'module',
scripts: {
test: 'node --experimental-vm-modules node_modules/jest/bin/jest.js',
},
};
// ============================================
// PART 2: JEST.CONFIG.MJS SETUP
// ============================================
// Disable CommonJS transforms so Jest evaluates native ESM syntax directly
export const jestConfig = {
testEnvironment: 'node',
transform: {},
verbose: true,
};
// ============================================
// PART 3: FILE URL PATH RESOLVER UTILITY
// ============================================
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
// Derive __filename and __dirname equivalents from import.meta.url
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export function getFixturePath(relativeFile) {
// Resolve paths relative to the current module directory
return resolve(__dirname, 'fixtures', relativeFile);
}
// ============================================
// PART 4: CREATE REQUIRE BRIDGE FOR JSON DATA
// ============================================
import { createRequire } from 'node:module';
// Anchor a CommonJS require function to this module's file URL
const require = createRequire(import.meta.url);
export function loadDefaultThresholds() {
// Safely import static JSON configuration without experimental assertions
return { minStock: 5, reorderMultiplier: 2 };
}
// ============================================
// PART 5: EXTERNAL REPOSITORY MODULE (TO BE MOCKED)
// ============================================
export async function fetchStockCount(sku) {
// In production, this queries a remote database
throw new Error(`Unmocked network call for SKU: ${sku}`);
}
export async function saveReorderAlert(sku, quantity) {
// In production, this publishes an event to a message broker
throw new Error(`Unmocked broker publish for SKU: ${sku}`);
}
// ============================================
// PART 6: DOMAIN SERVICE CONSUMING REPOSITORY
// ============================================
export async function evaluateInventoryLevel(sku, fetchFn, alertFn) {
const currentStock = await fetchFn(sku);
const { minStock, reorderMultiplier } = loadDefaultThresholds();
if (currentStock < minStock) {
const orderQty = minStock * reorderMultiplier;
await alertFn(sku, orderQty);
return { sku, status: 'REORDER_TRIGGERED', orderQty };
}
return { sku, status: 'HEALTHY', orderQty: 0 };
}
// ============================================
// PART 7: ASYNCHRONOUS ESM MOCK REGISTRATION
// ============================================
import { afterEach, describe, expect, it, jest } from '@jest/globals';
// Create mock functions for the repository exports
const mockFetchStockCount = jest.fn();
const mockSaveReorderAlert = jest.fn();
// Register the module mock before any dynamic import executes
jest.unstable_mockModule('./inventory-repo.js', () => ({
fetchStockCount: mockFetchStockCount,
saveReorderAlert: mockSaveReorderAlert,
}));
// ============================================
// PART 8: DYNAMIC IMPORT OF TARGET MODULE
// ============================================
// Load the mocked module dynamically after unstable_mockModule completes
const mockedRepo = await import('./inventory-repo.js');
// ============================================
// PART 9: TEST SUITE ASSERTIONS AND EXECUTION
// ============================================
describe('Inventory ESM Evaluation Suite', () => {
afterEach(() => {
// Clear mock call counts after every test case
jest.clearAllMocks();
});
it('triggers a reorder alert when stock falls below threshold', async () => {
// Configure mock stock level below minStock (5)
mockFetchStockCount.mockResolvedValue(2);
mockSaveReorderAlert.mockResolvedValue({ acknowledged: true });
const outcome = await evaluateInventoryLevel(
'SKU-900',
mockedRepo.fetchStockCount,
mockedRepo.saveReorderAlert
);
expect(outcome).toEqual({
sku: 'SKU-900',
status: 'REORDER_TRIGGERED',
orderQty: 10,
});
expect(mockSaveReorderAlert).toHaveBeenCalledWith('SKU-900', 10);
});
it('resolves valid filesystem paths from import.meta.url', () => {
const fixtureFile = getFixturePath('sample-stock.json');
expect(fixtureFile.startsWith('file://')).toBe(false);
expect(fixtureFile.endsWith('sample-stock.json')).toBe(true);
});
});
// ============================================
// PART 10: CLEANUP AND MODULE ISOLATION RESET
// ============================================
// Reset module registry state if additional isolated imports follow
jest.resetModules();
This ten-part session demonstrates the complete end-to-end lifecycle of a native ESM Jest setup, starting from package manifest flags and configuration files through import.meta.url path resolution, asynchronous module mocking with jest.unstable_mockModule(), and clean test execution.
Quick Reference
Runtime Flags and Manifest Settings
| Setting / Flag | Location | Effect |
--experimental-vm-modules | Node CLI command | Enables vm.SourceTextModule linking in Node.js for Jest |
"type": "module" | package.json | Instructs Node and Jest to parse .js files as native ESM |
transform: {} | jest.config.mjs | Disables default Babel CommonJS transpilation |
extensionsToTreatAsEsm | jest.config.mjs | Tells Jest to load .ts or .jsx files as native ES modules |
moduleNameMapper | jest.config.mjs | Rewrites .js relative import specifiers to resolve .ts files |
Native ESM Path and URL Utilities
| API / Property | Module | Return Value / Purpose |
import.meta.url | Native ECMAScript | Returns the file:// URL string of the current module |
fileURLToPath(url) | node:url | Converts a file:// URL into a decoded OS file path |
pathToFileURL(path) | node:url | Converts a local filesystem path into a valid file:// URL |
dirname(filePath) | node:path | Extracts the parent directory path (replaces __dirname) |
createRequire(url) | node:module | Creates a require() function anchored to a module URL |
Jest ESM Globals and Mocking APIs
| Method / Import | Source | Purpose |
import { jest } from '@jest/globals' | @jest/globals | Explicitly imports the Jest object inside isolated ESM scopes |
jest.unstable_mockModule(id, factory) | @jest/globals | Asynchronously registers an ESM mock factory before import() |
await import(specifier) | Native ECMAScript | Dynamically loads a module after mocks have been registered |
jest.resetModules() | @jest/globals | Clears Jest’s module registry cache between isolated tests |
Best Practices
โ Do This:
JavaScript
// Import jest explicitly from @jest/globals in native ESM test files
import { describe, expect, it, jest } from '@jest/globals'; // โ
// Convert import.meta.url with fileURLToPath before passing to path APIs
const __dirname = dirname(fileURLToPath(import.meta.url)); // โ
// Include explicit .js extensions on all relative ESM imports
import { parseInvoice } from '../src/invoice-parser.js'; // โ
// Register unstable_mockModule BEFORE calling dynamic await import()
jest.unstable_mockModule('../src/api.js', () => ({ fetch: jest.fn() })); // โ
const { loadUsers } = await import('../src/user-loader.js'); // โ
// Provide an explicit default key when mocking default-exported modules
jest.unstable_mockModule('../src/logger.js', () => ({ default: logFn }));// โ
// Use createRequire(import.meta.url) to load static JSON files cleanly
const require = createRequire(import.meta.url); // โ
const schema = require('./schema.json'); // โ
// Run Jest directly via node --experimental-vm-modules in npm scripts
// "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" // โ
โ Don’t Do This:
JavaScript
// Rely on implicit global jest object without importing from @jest/globals
const mockFn = jest.fn(); // ReferenceError: jest is not defined // โ
// Pass import.meta.url directly into fs.readFileSync or path.join
const badPath = join(import.meta.url, 'data.json'); // Invalid file:// // โ
// Omit file extensions on relative imports in native ESM files
import { parseInvoice } from '../src/invoice-parser'; // ERR_MODULE_NOT_FOUND // โ
// Mix static top-level imports with jest.unstable_mockModule()
jest.unstable_mockModule('../src/api.js', () => ({ fetch: jest.fn() })); // โ
import { loadUsers } from '../src/user-loader.js'; // Hoists before mock // โ
// Use legacy jest.mock() expecting automatic Babel hoisting in ESM
jest.mock('../src/api.js'); // Does not hoist in native ESM // โ
// Use CommonJS __dirname or __filename globals inside "type": "module"
const file = resolve(__dirname, 'config.json'); // ReferenceError // โ
// Run bare `jest` CLI without passing --experimental-vm-modules to Node
// "test": "jest" -> SyntaxError: Cannot use import statement // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
SyntaxError: Cannot use import statement outside a module | Node executed Jest without --experimental-vm-modules or package.json lacks "type": "module" | Add "type": "module" to package.json and run node --experimental-vm-modules node_modules/jest/bin/jest.js |
ReferenceError: jest is not defined | Native ESM enforces strict module scope isolation and does not inject CommonJS globals | Explicitly import { jest, describe, it, expect } from @jest/globals at the top of every test file |
jest.unstable_mockModule() has no effect on imported code | Static import statements are resolved by Node before any test code executes | Replace static imports of mocked consumers with const mod = await import('./mod.js') after registering the mock |
ERR_MODULE_NOT_FOUND on relative imports | Native ESM requires explicit file extensions and does not auto-append .js or /index.js | Append .js to all relative import specifiers (even when authoring .ts files) |
ENOENT: no such file or directory, open 'file:/...' | Passing import.meta.url directly to fs or path functions leaves the file:// URL protocol intact | Wrap import.meta.url with fileURLToPath(import.meta.url) from node:url first |
SyntaxError: The requested module does not provide an export named 'default' | A mock factory passed to jest.unstable_mockModule() omitted the default property | Add default: mockImplementation inside the factory object returned by jest.unstable_mockModule() |
ReferenceError: __dirname is not defined | Node omits CommonJS wrapper variables (__dirname, __filename, require) in ESM files | Derive __dirname using dirname(fileURLToPath(import.meta.url)) |
Real-World Examples
1. Invoking Jest with Experimental VM Modules in Package Scripts
JSON
{
"type": "module",
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand"
}
}
2. Resolving Test Fixture Paths Using fileURLToPath
JavaScript
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const fixturesDir = join(dirname(fileURLToPath(import.meta.url)), '__fixtures__');
3. Mocking a Named Export Module Asynchronously
JavaScript
import { jest } from '@jest/globals';
jest.unstable_mockModule('../src/token-signer.js', () => ({
signJwt: jest.fn().mockResolvedValue('signed.token.value'),
}));
const { issueSession } = await import('../src/auth-controller.js');
4. Mocking a Default Export Module Asynchronously
JavaScript
import { jest } from '@jest/globals';
jest.unstable_mockModule('../src/redis-client.js', () => ({
default: { get: jest.fn().mockResolvedValue('cached_payload') },
}));
const { getCachedProfile } = await import('../src/profile-cache.js');
5. Loading Legacy CommonJS Modules Inside an ESM Test
JavaScript
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const legacyValidator = require('../legacy/schema-validator.cjs');
6. Configuring TypeScript Extension Mapping in jest.config.mjs
JavaScript
export default {
testEnvironment: 'node',
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1' },
transform: { '^.+\\.tsx?$': ['ts-jest', { useESM: true }] },
};
7. Converting a Filesystem Path Back to a File URL
JavaScript
import { pathToFileURL } from 'node:url';
import { resolve } from 'node:path';
const moduleUrl = pathToFileURL(resolve('./plugins/custom-hook.js')).href;
8. Resetting Module Registry Between Isolated Dynamic Imports
JavaScript
import { beforeEach, jest } from '@jest/globals';
beforeEach(() => {
jest.resetModules();
});
9. Spying on a Dynamically Imported ESM Namespace
JavaScript
import { jest } from '@jest/globals';
const mathUtils = await import('../src/math-utils.js');
const spy = jest.spyOn(mathUtils, 'calculateTax').mockReturnValue(25);
10. Checking Current Module Execution URL in Standalone Scripts
JavaScript
import { fileURLToPath } from 'node:url';
const isDirectEntry = process.argv[1] === fileURLToPath(import.meta.url);
Visual
The Native ESM Jest Execution Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 1. NODE PROCESS STARTUP โ
โ node --experimental-vm-modules node_modules/jest/bin/jest.js โ
โ Unlocks vm.SourceTextModule & vm.SyntheticModule in V8 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 2. MANIFEST & CONFIG RESOLUTION โ
โ Reads package.json ("type": "module") and jest.config.mjs โ
โ Applies moduleNameMapper & extensionsToTreatAsEsm rules โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 3. MOCK REGISTRATION PHASE (TOP-LEVEL AWAIT) โ
โ jest.unstable_mockModule() registers virtual module factories โ
โ before target modules enter the asynchronous linker graph โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 4. ASYNCHRONOUS LINKING & EVALUATION โ
โ await import('./service.js') links mocked dependencies, โ
โ populates import.meta.url, and executes Jest assertions โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
CommonJS Hoisting vs. Native ESM Linking Order
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ COMMONJS EXECUTION (LEGACY) โ โ NATIVE ESM EXECUTION (MODERN) โ
โ โ โ โ
โ 1. Babel hoists jest.mock() โ โ 1. Static imports link FIRST โ
โ to line 1 automatically โ โ (before test code runs) โ
โ โ โ โ
โ 2. require() intercepts calls โ โ 2. unstable_mockModule() runs โ
โ synchronously at runtime โ โ during top-level execution โ
โ โ โ โ
โ 3. Mocked exports apply to โ โ 3. Dynamic await import() โ
โ all standard imports โ โ binds the registered mocks โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
File URL to Filesystem Path Conversion Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ import.meta.url โ
โ "file:///home/dev/app/src/config%20loader.js" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ fileURLToPath() from 'node:url'
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Decoded OS File Path (__filename equivalent) โ
โ "/home/dev/app/src/config loader.js" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ dirname() from 'node:path'
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Parent Directory Path (__dirname equivalent) โ
โ "/home/dev/app/src" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Dual-Package Hazard vs. Unified ESM Registry
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ COMMONJS EMULATION (SPLIT REGISTRY) โ
โ Test File โโโบ require('pkg') โโโบ CommonJS Instance A โ
โ ESM Dep โโโบ import('pkg') โโโบ ESM Instance B (instanceof fails!) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ Switch to --experimental-vm-modules
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ NATIVE ESM MODE (UNIFIED REGISTRY) โ
โ Test File โโโบ import('pkg') โโโ โ
โ โโโโบ Single Shared ESM Instance โ
โ ESM Dep โโโบ import('pkg') โโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
| Runtime Flag | node --experimental-vm-modules |
| Package Manifest | "type": "module" in package.json |
| Config File Format | jest.config.mjs with transform: {} |
| Globals Import | import { jest, describe, it, expect } from '@jest/globals' |
| Module Metadata | import.meta.url (returns file:// URL string) |
| Path Conversion | fileURLToPath(import.meta.url) from node:url |
| Directory Helper | dirname(fileURLToPath(import.meta.url)) from node:path |
| CommonJS Bridge | createRequire(import.meta.url) from node:module |
| ESM Mocking API | jest.unstable_mockModule(specifier, factory) |
| Consumer Loading | const mod = await import('./target.js') |
Key takeaways:
- Node VM modules flag. Jest requires
node --experimental-vm-modulesto instantiate native ECMAScript module graphs without falling back to CommonJS transpilation. - Explicit Jest globals. Native ESM isolates module scopes, requiring explicit imports of
jest,describe,it, andexpectfrom@jest/globals. - Mandatory file extensions. Relative imports inside native ESM projects must include explicit extensions such as
.js, even when mapping to TypeScript source files viamoduleNameMapper. - File URL decoding. Always convert
import.meta.urlwithfileURLToPath()before passing module paths tonode:fsornode:pathutilities. - Asynchronous mock registration. Because static imports link before code runs, replace hoisted
jest.mock()calls withjest.unstable_mockModule()followed by dynamicawait import(). - Explicit default exports. When mocking modules with default exports in ESM, your
unstable_mockModulefactory must return an object containing adefaultkey. - CommonJS interoperability. Use
createRequire(import.meta.url)whenever an ESM test or utility needs to load static JSON files or legacy.cjsmodules synchronously.
Remember: Testing native ECMAScript Modules in Jest eliminates CommonJS transformation discrepancies and prevents the dual-package hazard, provided you align your Node CLI flags, URL-based file path utilities, and asynchronous mocking lifecycle. By combining fileURLToPath(import.meta.url) for deterministic path resolution with jest.unstable_mockModule() and dynamic import() for dependency isolation, your test suite mirrors real production module semantics accurately.
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!