Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import.meta.resolve support #14930

Merged
merged 11 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions e2e/native-esm/__tests__/native-esm.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ test('should have correct import.meta', () => {
expect(
import.meta.url.endsWith('/e2e/native-esm/__tests__/native-esm.test.js'),
).toBe(true);
expect(import.meta.resolve('colors'))
.endsWith('jest/node_modules/colors/lib/index.js')
CheadleCheadle marked this conversation as resolved.
Show resolved Hide resolved
.toBe(true);
expect(import.meta.resolve('./native-esm.test'))
.endsWith('jest/e2e/native-esm/__tests__/native-esm.test.js')
.toBe(true);

if (process.platform === 'win32') {
expect(
import.meta.filename.endsWith(
Expand Down
56 changes: 54 additions & 2 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import nativeModule = require('module');
import * as path from 'path';
import {URL, fileURLToPath, pathToFileURL} from 'url';
Expand All @@ -21,6 +20,7 @@
import {parse as parseCjs} from 'cjs-module-lexer';
import {CoverageInstrumenter, type V8Coverage} from 'collect-v8-coverage';
import * as fs from 'graceful-fs';
import type {ResolverConfig} from 'jest-resolve/src/types';
import slash = require('slash');
import stripBOM = require('strip-bom');
import type {
Expand All @@ -47,7 +47,11 @@
shouldInstrument,
} from '@jest/transform';
import type {Config, Global} from '@jest/types';
import HasteMap, {type IHasteMap, type IModuleMap} from 'jest-haste-map';
import HasteMap, {
type IHasteMap,
type IModuleMap,
ModuleMap,
} from 'jest-haste-map';
import {formatStackTrace, separateMessageFromStack} from 'jest-message-util';
import type {MockMetadata, ModuleMocker} from 'jest-mock';
import {escapePathForRegex} from 'jest-regex-util';
Expand Down Expand Up @@ -525,6 +529,54 @@
// @ts-expect-error Jest uses @types/node@16. Will be fixed when updated to @types/[email protected]
meta.dirname = path.dirname(meta.filename);

meta.resolve = (

Check failure on line 532 in packages/jest-runtime/src/index.ts

View workflow job for this annotation

GitHub Actions / Typecheck Examples and Tests

Type '(specifier: string, parent?: string | URL) => string | null' is not assignable to type '(specified: string, parent?: string | URL | undefined) => Promise<string>'.

Check failure on line 532 in packages/jest-runtime/src/index.ts

View workflow job for this annotation

GitHub Actions / TypeScript Compatibility

Type '(specifier: string, parent?: string | URL) => string | null' is not assignable to type '(specified: string, parent?: string | URL | undefined) => Promise<string>'.
CheadleCheadle marked this conversation as resolved.
Show resolved Hide resolved
specifier: string,
parent?: string | URL,
): string | null => {
CheadleCheadle marked this conversation as resolved.
Show resolved Hide resolved
let filename;
let dirname;

if (typeof parent === 'string') {
// Check if parent is a valid file URL
if (parent.startsWith('file:///')) {
filename = path.resolve(fileURLToPath(parent), specifier);
dirname = `./${parent.replace('file:///', '')}`; // Convert file URL to relative path
} else {
// Parent is a non-URL string; treat as a file path
filename = path.resolve(parent, specifier);
dirname = parent;
}
} else {
// No valid parent provided fallback to module's URL
filename = fileURLToPath(meta.url);
dirname = path.dirname(filename);
}

// Configure the module resolver
const moduleMap = ModuleMap.create('/');
const resolver = new Resolver(moduleMap, {
defaultPlatform: 'node',
extensions: ['.js', '.json', '.ts', '.node', '.mjs'],
hasCoreModules: false,
} as ResolverConfig);

const resolvedPath = resolver.resolveModuleFromDirIfExists(
dirname,
specifier,
);

// Check resolution result and format output
if (resolvedPath) {
// Convert the resolved path back to a URL if sparent was originally a URL otherwise return the path
return typeof parent === 'string' &&
parent.startsWith('file:///')
? pathToFileURL(resolvedPath).href
: resolvedPath;
} else {
return null;
}
};

let jest = this.jestObjectCaches.get(modulePath);

if (!jest) {
Expand Down
Loading