| | |

Jest 17 ๐Ÿƒ ESM Support โ€” Native ESM, import.meta, and file URL handling

โฑ๏ธ Estimated read: 19 min | |

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 / FlagLocationEffect
--experimental-vm-modulesNode CLI commandEnables vm.SourceTextModule linking in Node.js for Jest
"type": "module"package.jsonInstructs Node and Jest to parse .js files as native ESM
transform: {}jest.config.mjsDisables default Babel CommonJS transpilation
extensionsToTreatAsEsmjest.config.mjsTells Jest to load .ts or .jsx files as native ES modules
moduleNameMapperjest.config.mjsRewrites .js relative import specifiers to resolve .ts files

Native ESM Path and URL Utilities

API / PropertyModuleReturn Value / Purpose
import.meta.urlNative ECMAScriptReturns the file:// URL string of the current module
fileURLToPath(url)node:urlConverts a file:// URL into a decoded OS file path
pathToFileURL(path)node:urlConverts a local filesystem path into a valid file:// URL
dirname(filePath)node:pathExtracts the parent directory path (replaces __dirname)
createRequire(url)node:moduleCreates a require() function anchored to a module URL

Jest ESM Globals and Mocking APIs

Method / ImportSourcePurpose
import { jest } from '@jest/globals'@jest/globalsExplicitly imports the Jest object inside isolated ESM scopes
jest.unstable_mockModule(id, factory)@jest/globalsAsynchronously registers an ESM mock factory before import()
await import(specifier)Native ECMAScriptDynamically loads a module after mocks have been registered
jest.resetModules()@jest/globalsClears 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

PitfallWhy It HappensFix
SyntaxError: Cannot use import statement outside a moduleNode 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 definedNative ESM enforces strict module scope isolation and does not inject CommonJS globalsExplicitly import { jest, describe, it, expect } from @jest/globals at the top of every test file
jest.unstable_mockModule() has no effect on imported codeStatic import statements are resolved by Node before any test code executesReplace static imports of mocked consumers with const mod = await import('./mod.js') after registering the mock
ERR_MODULE_NOT_FOUND on relative importsNative ESM requires explicit file extensions and does not auto-append .js or /index.jsAppend .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 intactWrap 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 propertyAdd default: mockImplementation inside the factory object returned by jest.unstable_mockModule()
ReferenceError: __dirname is not definedNode omits CommonJS wrapper variables (__dirname, __filename, require) in ESM filesDerive __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

ItemValue
Runtime Flagnode --experimental-vm-modules
Package Manifest"type": "module" in package.json
Config File Formatjest.config.mjs with transform: {}
Globals Importimport { jest, describe, it, expect } from '@jest/globals'
Module Metadataimport.meta.url (returns file:// URL string)
Path ConversionfileURLToPath(import.meta.url) from node:url
Directory Helperdirname(fileURLToPath(import.meta.url)) from node:path
CommonJS BridgecreateRequire(import.meta.url) from node:module
ESM Mocking APIjest.unstable_mockModule(specifier, factory)
Consumer Loadingconst mod = await import('./target.js')

Key takeaways:

  • Node VM modules flag. Jest requires node --experimental-vm-modules to 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, and expect from @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 via moduleNameMapper.
  • File URL decoding. Always convert import.meta.url with fileURLToPath() before passing module paths to node:fs or node:path utilities.
  • Asynchronous mock registration. Because static imports link before code runs, replace hoisted jest.mock() calls with jest.unstable_mockModule() followed by dynamic await import().
  • Explicit default exports. When mocking modules with default exports in ESM, your unstable_mockModule factory must return an object containing a default key.
  • CommonJS interoperability. Use createRequire(import.meta.url) whenever an ESM test or utility needs to load static JSON files or legacy .cjs modules 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.

Was this helpful?


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!