From 83ddddbbddcdc36bd9d6bf55b6864ffa0fdb5f2c Mon Sep 17 00:00:00 2001 From: Peter Leonov Date: Mon, 14 May 2018 19:53:09 +0200 Subject: [PATCH 1/6] craft a test --- .../src/__mocks__/resourceQueryResolver.js | 14 +++++++ .../__tests__/runtime_require_module.test.js | 41 +++++++++++++++++++ .../test_root/moduleForResourceQuery.js | 11 +++++ 3 files changed, 66 insertions(+) create mode 100644 packages/jest-runtime/src/__mocks__/resourceQueryResolver.js create mode 100644 packages/jest-runtime/src/__tests__/test_root/moduleForResourceQuery.js diff --git a/packages/jest-runtime/src/__mocks__/resourceQueryResolver.js b/packages/jest-runtime/src/__mocks__/resourceQueryResolver.js new file mode 100644 index 000000000000..cfaf6fd46271 --- /dev/null +++ b/packages/jest-runtime/src/__mocks__/resourceQueryResolver.js @@ -0,0 +1,14 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +module.exports = function userResolver(path, options) { + const defaultResolver = require('../__tests__/defaultResolver.js'); + const [clearPath, query] = path.split('?'); + return defaultResolver(clearPath, options) + (query ? '?' + query : ''); +}; diff --git a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js index 685667dea150..b60d65f09d98 100644 --- a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js +++ b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js @@ -252,6 +252,47 @@ describe('Runtime requireModule', () => { expect(hastePackage.isHastePackage).toBe(true); })); + it('supports resolving the same path to multiple modules', () => + createRuntime(__filename, { + // using the default resolver as a custom resolver + resolver: require.resolve('../__mocks__/resourceQueryResolver.js'), + }).then(runtime => { + const moduleNoQuery1 = runtime.requireModule( + runtime.__mockRootPath, + './moduleForResourceQuery.js', + ); + const moduleNoQuery2 = runtime.requireModule( + runtime.__mockRootPath, + './moduleForResourceQuery.js', + ); + expect(moduleNoQuery1.name).toBe('moduleForResourceQuery'); + expect(moduleNoQuery1).toBe(moduleNoQuery2); + + const moduleWithQueryA = runtime.requireModule( + runtime.__mockRootPath, + './moduleForResourceQuery.js?a', + ); + const moduleWithQueryB = runtime.requireModule( + runtime.__mockRootPath, + './moduleForResourceQuery.js?b', + ); + expect(moduleWithQueryA.name).toBe('moduleForResourceQuery'); + expect(moduleWithQueryB.name).toBe('moduleForResourceQuery'); + expect(moduleWithQueryA).not.toBe(moduleWithQueryB); + + const moduleWithSameQuery1 = runtime.requireModule( + runtime.__mockRootPath, + './moduleForResourceQuery.js?sameQuery', + ); + const moduleWithSameQuery2 = runtime.requireModule( + runtime.__mockRootPath, + './moduleForResourceQuery.js?sameQuery', + ); + expect(moduleWithSameQuery1.name).toBe('moduleForResourceQuery'); + expect(moduleWithSameQuery2.name).toBe('moduleForResourceQuery'); + expect(moduleWithSameQuery1).toBe(moduleWithSameQuery2); + })); + it('resolves node modules properly when crawling node_modules', () => // While we are crawling a node module, we shouldn't put package.json // files of node modules to resolve to `package.json` but rather resolve diff --git a/packages/jest-runtime/src/__tests__/test_root/moduleForResourceQuery.js b/packages/jest-runtime/src/__tests__/test_root/moduleForResourceQuery.js new file mode 100644 index 000000000000..ddc4688b8b2a --- /dev/null +++ b/packages/jest-runtime/src/__tests__/test_root/moduleForResourceQuery.js @@ -0,0 +1,11 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// this object reference should be uniq per each module compilation +const newObject = {name: 'moduleForResourceQuery'}; + +module.exports = newObject; From 46712583461f78dfdc0f939e3b6b7fc40dfa3058 Mon Sep 17 00:00:00 2001 From: Peter Leonov Date: Mon, 10 Feb 2020 23:24:27 +0100 Subject: [PATCH 2/6] add the stub type --- packages/jest-types/src/Config.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/jest-types/src/Config.ts b/packages/jest-types/src/Config.ts index 7169f8e13f18..8713f523792c 100644 --- a/packages/jest-types/src/Config.ts +++ b/packages/jest-types/src/Config.ts @@ -12,6 +12,20 @@ import chalk = require('chalk'); type CoverageProvider = 'babel' | 'v8'; export type Path = string; +export type PathID = string; +// Keeping RPth of the same length as Path for now, to keep diffs to minimum +// will rename it later. +export type RPth = { + // the initial path as it was used before this PR + // replace it with other properties: + // 1. realpath - full path resolved using smth. like _getRealPath() + // 2. filename - just the file name w/o the containing directies + // 3. extname - just the extension (to speed up a bit) + // 4. dirname - just the dir name (to speed up a bit) + readonly path: string + // prob. the real path + the query string + readonly id: PathID, +}; export type Glob = string; From 7f2364686c4d83486c3ca10830752523f1707430 Mon Sep 17 00:00:00 2001 From: Peter Leonov Date: Sun, 29 Mar 2020 18:54:48 +0200 Subject: [PATCH 3/6] add the type guided by TS --- .../jest-reporters/src/coverage_worker.ts | 2 +- .../src/generateEmptyCoverage.ts | 8 +-- packages/jest-runtime/src/index.ts | 10 ++- .../jest-transform/src/ScriptTransformer.ts | 72 +++++++++++-------- packages/jest-types/src/Config.ts | 4 +- 5 files changed, 55 insertions(+), 41 deletions(-) diff --git a/packages/jest-reporters/src/coverage_worker.ts b/packages/jest-reporters/src/coverage_worker.ts index 23109ffa16ee..e12db311ab65 100644 --- a/packages/jest-reporters/src/coverage_worker.ts +++ b/packages/jest-reporters/src/coverage_worker.ts @@ -37,7 +37,7 @@ export function worker({ }: CoverageWorkerData): CoverageWorkerResult | null { return generateEmptyCoverage( fs.readFileSync(path, 'utf8'), - path, + {id: path, path}, globalConfig, config, options && options.changedFiles && new Set(options.changedFiles), diff --git a/packages/jest-reporters/src/generateEmptyCoverage.ts b/packages/jest-reporters/src/generateEmptyCoverage.ts index 62ab4c023f2c..a595e17cd9ee 100644 --- a/packages/jest-reporters/src/generateEmptyCoverage.ts +++ b/packages/jest-reporters/src/generateEmptyCoverage.ts @@ -27,7 +27,7 @@ export type CoverageWorkerResult = export default function ( source: string, - filename: Config.Path, + filename: Config.RPth, globalConfig: Config.GlobalConfig, config: Config.ProjectConfig, changedFiles?: Set, @@ -40,9 +40,9 @@ export default function ( coverageProvider: globalConfig.coverageProvider, }; let coverageWorkerResult: CoverageWorkerResult | null = null; - if (shouldInstrument(filename, coverageOptions, config)) { + if (shouldInstrument(filename.path, coverageOptions, config)) { if (coverageOptions.coverageProvider === 'v8') { - const stat = fs.statSync(filename); + const stat = fs.statSync(filename.path); return { kind: 'V8Coverage', result: { @@ -60,7 +60,7 @@ export default function ( }, ], scriptId: '0', - url: filename, + url: filename.path, }, }; } diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index cfef2ebf1704..1804d8eed1ee 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -55,7 +55,9 @@ type InternalModuleOptions = { }; type InitialModule = Partial & - Pick; + Pick & { + rpth: Config.RPth; + }; type ModuleRegistry = Map; type ResolveOptions = Parameters[1]; @@ -352,6 +354,7 @@ class Runtime { filename: modulePath, id: modulePath, loaded: false, + rpth: {id: 'InitialModule', path: modulePath}, }; moduleRegistry.set(modulePath, localModule); @@ -442,6 +445,7 @@ class Runtime { filename: modulePath, id: modulePath, loaded: false, + rpth: {id: 'InitialModule', path: modulePath}, }; this._loadModule( @@ -746,7 +750,7 @@ class Runtime { localModule: InitialModule, options: InternalModuleOptions | undefined, moduleRegistry: ModuleRegistry, - from: Config.Path | null, + from: Config.Path | null, // RPth? ) { // If the environment was disposed, prevent this module from being executed. if (!this._environment.global) { @@ -775,7 +779,7 @@ class Runtime { value: this._createRequireImplementation(localModule, options), }); const transformedFile = this._scriptTransformer.transform( - filename, + localModule.rpth, this._getFullTransformationOptions(options), this._cacheFS[filename], ); diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index a3658842f164..a4dc3fe797e6 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -88,36 +88,44 @@ export default class ScriptTransformer { private _getCacheKey( fileData: string, - filename: Config.Path, + filename: Config.RPth, instrument: boolean, ): string { const configString = this._cache.configString; - const transformer = this._getTransformer(filename); + const transformer = this._getTransformer(filename.path); if (transformer && typeof transformer.getCacheKey === 'function') { - return createHash('md5') - .update( - transformer.getCacheKey(fileData, filename, configString, { - config: this._config, - instrument, - rootDir: this._config.rootDir, - }), - ) - .update(CACHE_VERSION) - .digest('hex'); + return ( + createHash('md5') + .update( + transformer.getCacheKey(fileData, filename.path, configString, { + config: this._config, + instrument, + rootDir: this._config.rootDir, + }), + ) + .update(CACHE_VERSION) + // required for the query string support + .update(filename.id) + .digest('hex') + ); } else { - return createHash('md5') - .update(fileData) - .update(configString) - .update(instrument ? 'instrument' : '') - .update(filename) - .update(CACHE_VERSION) - .digest('hex'); + return ( + createHash('md5') + .update(fileData) + .update(configString) + .update(instrument ? 'instrument' : '') + .update(filename.path) + // required for the query string support + .update(filename.id) + .update(CACHE_VERSION) + .digest('hex') + ); } } private _getFileCachePath( - filename: Config.Path, + filename: Config.RPth, content: string, instrument: boolean, ): Config.Path { @@ -131,7 +139,7 @@ export default class ScriptTransformer { // directory with many files. const cacheDir = path.join(baseCacheDir, cacheKey[0] + cacheKey[1]); const cacheFilenamePrefix = path - .basename(filename, path.extname(filename)) + .basename(filename.path, path.extname(filename.path)) .replace(/\W/g, ''); const cachePath = slash( path.join(cacheDir, cacheFilenamePrefix + '_' + cacheKey), @@ -252,13 +260,13 @@ export default class ScriptTransformer { } transformSource( - filepath: Config.Path, + filepath: Config.RPth, content: string, instrument: boolean, ): TransformResult { - const filename = this._getRealPath(filepath); + const filename = this._getRealPath(filepath.path); const transform = this._getTransformer(filename); - const cacheFilePath = this._getFileCachePath(filename, content, instrument); + const cacheFilePath = this._getFileCachePath(filepath, content, instrument); let sourceMapPath: Config.Path | null = cacheFilePath + '.map'; // Ignore cache if `config.cache` is set (--no-cache) let code = this._config.cache ? readCodeCacheFile(cacheFilePath) : null; @@ -374,7 +382,7 @@ export default class ScriptTransformer { } private _transformAndBuildScript( - filename: Config.Path, + filename: Config.RPth, options: Options | null, instrument: boolean, fileSource?: string, @@ -382,7 +390,7 @@ export default class ScriptTransformer { const isInternalModule = !!(options && options.isInternalModule); const isCoreModule = !!(options && options.isCoreModule); const content = stripShebang( - fileSource || fs.readFileSync(filename, 'utf8'), + fileSource || fs.readFileSync(filename.path, 'utf8'), ); let code = content; @@ -392,7 +400,7 @@ export default class ScriptTransformer { const willTransform = !isInternalModule && !isCoreModule && - (this.shouldTransform(filename) || instrument); + (this.shouldTransform(filename.path) || instrument); try { if (willTransform) { @@ -419,7 +427,7 @@ export default class ScriptTransformer { } transform( - filename: Config.Path, + filename: Config.RPth, options: Options, fileSource?: string, ): TransformResult { @@ -429,7 +437,7 @@ export default class ScriptTransformer { if (!options.isCoreModule) { instrument = options.coverageProvider === 'babel' && - shouldInstrument(filename, options, this._config); + shouldInstrument(filename.path, options, this._config); scriptCacheKey = getScriptCacheKey(filename, instrument); const result = this._cache.transformedFiles.get(scriptCacheKey); if (result) { @@ -463,6 +471,7 @@ export default class ScriptTransformer { if (willTransform) { const {code: transformedJsonSource} = this.transformSource( + // @ts-ignore filename, fileSource, false, @@ -494,6 +503,7 @@ export default class ScriptTransformer { (code, filename) => { try { transforming = true; + // @ts-ignore return this.transformSource(filename, code, false).code || code; } finally { transforming = false; @@ -686,8 +696,8 @@ const readCacheFile = (cachePath: Config.Path): string | null => { return fileData; }; -const getScriptCacheKey = (filename: Config.Path, instrument: boolean) => { - const mtime = fs.statSync(filename).mtime; +const getScriptCacheKey = (filename: Config.RPth, instrument: boolean) => { + const mtime = fs.statSync(filename.path).mtime; return filename + '_' + mtime.getTime() + (instrument ? '_instrumented' : ''); }; diff --git a/packages/jest-types/src/Config.ts b/packages/jest-types/src/Config.ts index 8713f523792c..1e7aca1b4fff 100644 --- a/packages/jest-types/src/Config.ts +++ b/packages/jest-types/src/Config.ts @@ -22,9 +22,9 @@ export type RPth = { // 2. filename - just the file name w/o the containing directies // 3. extname - just the extension (to speed up a bit) // 4. dirname - just the dir name (to speed up a bit) - readonly path: string + readonly path: string; // prob. the real path + the query string - readonly id: PathID, + readonly id: PathID; }; export type Glob = string; From 36754bbea7fd73c04ded676518bcc40b746fd7ea Mon Sep 17 00:00:00 2001 From: Peter Leonov Date: Sun, 29 Mar 2020 18:57:18 +0200 Subject: [PATCH 4/6] add query parsing to findNodeModule() and friends --- packages/jest-resolve/src/index.ts | 85 +++++++++++++++++++++--------- 1 file changed, 60 insertions(+), 25 deletions(-) diff --git a/packages/jest-resolve/src/index.ts b/packages/jest-resolve/src/index.ts index 15856fb5aeb2..99e12a0de03d 100644 --- a/packages/jest-resolve/src/index.ts +++ b/packages/jest-resolve/src/index.ts @@ -49,12 +49,18 @@ const nodePaths = NODE_PATH .map(p => path.resolve(resolvedCwd, p)) : undefined; +function parseOutQuery(pathQithQuery: string) { + const [path, ...queryParts] = pathQithQuery.split('?') + const query = queryParts.join('') + return [path, query] +} + /* eslint-disable-next-line no-redeclare */ class Resolver { private readonly _options: ResolverConfig; private readonly _moduleMap: ModuleMap; private readonly _moduleIDCache: Map; - private readonly _moduleNameCache: Map; + private readonly _moduleNameCache: Map; private readonly _modulePathCache: Map>; private readonly _supportsNativePlatform: boolean; @@ -105,14 +111,15 @@ class Resolver { static findNodeModule( path: Config.Path, options: FindNodeModuleConfig, - ): Config.Path | null { + ): Config.RPth | null { const resolver: typeof defaultResolver = options.resolver ? require(options.resolver) : defaultResolver; const paths = options.paths; try { - return resolver(path, { + const [nativePath, query] = parseOutQuery(path) + const realpath = resolver(nativePath, { basedir: options.basedir, browser: options.browser, defaultResolver, @@ -121,6 +128,11 @@ class Resolver { paths: paths ? (nodePaths || []).concat(paths) : nodePaths, rootDir: options.rootDir, }); + + return { + path: realpath, + id: `${realpath}?${query}` + } } catch (e) { if (options.throwIfNotFound) { throw e; @@ -133,13 +145,12 @@ class Resolver { dirname: Config.Path, moduleName: string, options?: Resolver.ResolveModuleConfig, - ): Config.Path | null { + ): Config.RPth | null { const paths = (options && options.paths) || this._options.modulePaths; const moduleDirectory = this._options.moduleDirectories; const key = dirname + path.delimiter + moduleName; const defaultPlatform = this._options.defaultPlatform; const extensions = this._options.extensions.slice(); - let module; if (this._supportsNativePlatform) { extensions.unshift( @@ -152,6 +163,8 @@ class Resolver { ); } + const [nativeName, query] = parseOutQuery(moduleName); + // 1. If we have already resolved this module for this directory name, // return a value from the cache. const cacheResult = this._moduleNameCache.get(key); @@ -160,10 +173,14 @@ class Resolver { } // 2. Check if the module is a haste module. - module = this.getModule(moduleName); - if (module) { - this._moduleNameCache.set(key, module); - return module; + const hasteModule = this.getModule(nativeName); + if (hasteModule) { + const resolvedPath = { + path: hasteModule, + id: `haste:${hasteModule}?${query}` + } + this._moduleNameCache.set(key, resolvedPath); + return resolvedPath; } // 3. Check if the module is a node module and resolve it based on @@ -189,11 +206,11 @@ class Resolver { if (!skipResolution) { // @ts-ignore: the "pnp" version named isn't in DefinitelyTyped - module = resolveNodeModule(moduleName, Boolean(process.versions.pnp)); + const nodeModule = resolveNodeModule(moduleName, Boolean(process.versions.pnp)); - if (module) { - this._moduleNameCache.set(key, module); - return module; + if (nodeModule) { + this._moduleNameCache.set(key, nodeModule); + return nodeModule; } } @@ -202,15 +219,22 @@ class Resolver { const parts = moduleName.split('/'); const hastePackage = this.getPackage(parts.shift()!); if (hastePackage) { + const requireResolve = (name: string) => { + const path = require.resolve(name) + return { + path, + id: `haste:${path}?${query}` + } + } try { - const module = path.join.apply( + const hastePackageModule = path.join.apply( path, [path.dirname(hastePackage)].concat(parts), ); // try resolving with custom resolver first to support extensions, // then fallback to require.resolve const resolvedModule = - resolveNodeModule(module) || require.resolve(module); + resolveNodeModule(hastePackageModule) || requireResolve(hastePackageModule); this._moduleNameCache.set(key, resolvedModule); return resolvedModule; } catch (ignoredError) {} @@ -223,7 +247,7 @@ class Resolver { from: Config.Path, moduleName: string, options?: Resolver.ResolveModuleConfig, - ): Config.Path { + ): Config.RPth { const dirname = path.dirname(from); const module = this.resolveStubModuleName(from, moduleName) || @@ -288,7 +312,7 @@ class Resolver { } else { const moduleName = this.resolveStubModuleName(from, name); if (moduleName) { - return this.getModule(moduleName) || moduleName; + return this.getModule(moduleName.path) || moduleName.path; } } return null; @@ -373,7 +397,7 @@ class Resolver { return virtualMocks[virtualMockPath] ? virtualMockPath : moduleName - ? this.resolveModule(from, moduleName) + ? this.resolveModule(from, moduleName).path : from; } @@ -386,7 +410,7 @@ class Resolver { resolveStubModuleName( from: Config.Path, moduleName: string, - ): Config.Path | null { + ): Config.RPth | null { const dirname = path.dirname(from); const paths = this._options.modulePaths; const extensions = this._options.extensions.slice(); @@ -407,12 +431,14 @@ class Resolver { ); } + const [nativeName, query] = parseOutQuery(moduleName); + if (moduleNameMapper) { for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) { - if (regex.test(moduleName)) { + if (regex.test(nativeName)) { // Note: once a moduleNameMapper matches the name, it must result // in a module, or else an error is thrown. - const matches = moduleName.match(regex); + const matches = nativeName.match(regex); const mapModuleName = matches ? (moduleName: string) => moduleName.replace( @@ -424,12 +450,20 @@ class Resolver { const possibleModuleNames = Array.isArray(mappedModuleName) ? mappedModuleName : [mappedModuleName]; - let module: string | null = null; + let module: Config.RPth | null = null; for (const possibleModuleName of possibleModuleNames) { const updatedName = mapModuleName(possibleModuleName); - module = - this.getModule(updatedName) || + const hasteModule = this.getModule(updatedName) + if (hasteModule) { + module = { + path: hasteModule, + id: `haste:${hasteModule}?${query}` + } + break + } + + const nodeModule = Resolver.findNodeModule(updatedName, { basedir: dirname, browser: this._options.browser, @@ -440,7 +474,8 @@ class Resolver { rootDir: this._options.rootDir, }); - if (module) { + if (nodeModule) { + module = nodeModule break; } } From c6f2e74db8818b2976b1d335bbb18d0174bd51dc Mon Sep 17 00:00:00 2001 From: Peter Leonov Date: Sun, 29 Mar 2020 19:28:49 +0200 Subject: [PATCH 5/6] stub further changes with `.path` --- packages/jest-config/src/normalize.ts | 6 +++--- packages/jest-config/src/utils.ts | 6 +++--- packages/jest-resolve-dependencies/src/index.ts | 2 +- packages/jest-runtime/src/index.ts | 9 +++++---- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/packages/jest-config/src/normalize.ts b/packages/jest-config/src/normalize.ts index 4fbf26ffc57e..55111b5b4bec 100644 --- a/packages/jest-config/src/normalize.ts +++ b/packages/jest-config/src/normalize.ts @@ -137,12 +137,12 @@ const setupPreset = ( // Force re-evaluation to support multiple projects try { if (presetModule) { - delete require.cache[require.resolve(presetModule)]; + delete require.cache[require.resolve(presetModule.path)]; } } catch (e) {} // @ts-ignore: `presetModule` can be null? - preset = require(presetModule); + preset = require(presetModule.path); } catch (error) { if (error instanceof SyntaxError || error instanceof TypeError) { throw createConfigError( @@ -435,7 +435,7 @@ const normalizeReporters = (options: Config.InitialOptionsWithRootDir) => { ` Module name: ${reporterPath}`, ); } - normalizedReporterConfig[0] = reporter; + normalizedReporterConfig[0] = reporter.path; } return normalizedReporterConfig; }); diff --git a/packages/jest-config/src/utils.ts b/packages/jest-config/src/utils.ts index ea093ff50747..360d85888e82 100644 --- a/packages/jest-config/src/utils.ts +++ b/packages/jest-config/src/utils.ts @@ -49,7 +49,7 @@ export const resolve = ( ); } /// can cast as string since nulls will be thrown - return module as string; + return module?.path as string; }; export const escapeGlobCharacters = (path: Config.Path): Config.Glob => @@ -139,7 +139,7 @@ export const resolveWithPrefix = ( resolver: resolver || undefined, }); if (module) { - return module; + return module.path; } try { @@ -151,7 +151,7 @@ export const resolveWithPrefix = ( resolver: resolver || undefined, }); if (module) { - return module; + return module.path; } try { diff --git a/packages/jest-resolve-dependencies/src/index.ts b/packages/jest-resolve-dependencies/src/index.ts index a16092ab73de..126c85664ac1 100644 --- a/packages/jest-resolve-dependencies/src/index.ts +++ b/packages/jest-resolve-dependencies/src/index.ts @@ -56,7 +56,7 @@ class DependencyResolver { file, dependency, options, - ); + ).path; } catch { try { resolvedDependency = this._resolver.getMockModule(file, dependency); diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index 1804d8eed1ee..ee8728ae4bec 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -675,8 +675,8 @@ class Runtime { this._moduleMocker.clearAllMocks(); } - private _resolveModule(from: Config.Path, to?: string) { - return to ? this._resolver.resolveModule(from, to) : from; + private _resolveModule(from: Config.Path, to?: string): string { + return to ? this._resolver.resolveModule(from, to).path : from; } private _requireResolve( @@ -702,7 +702,7 @@ class Runtime { {paths: [absolutePath]}, ); if (module) { - return module; + return module.path; } } @@ -939,6 +939,7 @@ class Runtime { filename, id: filename, loaded: false, + rpth: {id: 'InitialModule', path: filename} }); }; @@ -978,7 +979,7 @@ class Runtime { private _generateMock(from: Config.Path, moduleName: string) { const modulePath = - this._resolver.resolveStubModuleName(from, moduleName) || + this._resolver.resolveStubModuleName(from, moduleName)?.path || this._resolveModule(from, moduleName); if (!(modulePath in this._mockMetaDataCache)) { // This allows us to handle circular dependencies while generating an From 23c174f3e9ad6ebefebd698d433395c23d8a02f3 Mon Sep 17 00:00:00 2001 From: Peter Leonov Date: Sun, 29 Mar 2020 19:36:04 +0200 Subject: [PATCH 6/6] prettier --- packages/jest-resolve/src/index.ts | 61 ++++++++++++++++-------------- packages/jest-runtime/src/index.ts | 2 +- 2 files changed, 33 insertions(+), 30 deletions(-) diff --git a/packages/jest-resolve/src/index.ts b/packages/jest-resolve/src/index.ts index 99e12a0de03d..2cc6de287d1f 100644 --- a/packages/jest-resolve/src/index.ts +++ b/packages/jest-resolve/src/index.ts @@ -50,9 +50,9 @@ const nodePaths = NODE_PATH : undefined; function parseOutQuery(pathQithQuery: string) { - const [path, ...queryParts] = pathQithQuery.split('?') - const query = queryParts.join('') - return [path, query] + const [path, ...queryParts] = pathQithQuery.split('?'); + const query = queryParts.join(''); + return [path, query]; } /* eslint-disable-next-line no-redeclare */ @@ -118,7 +118,7 @@ class Resolver { const paths = options.paths; try { - const [nativePath, query] = parseOutQuery(path) + const [nativePath, query] = parseOutQuery(path); const realpath = resolver(nativePath, { basedir: options.basedir, browser: options.browser, @@ -130,9 +130,9 @@ class Resolver { }); return { + id: `${realpath}?${query}`, path: realpath, - id: `${realpath}?${query}` - } + }; } catch (e) { if (options.throwIfNotFound) { throw e; @@ -176,9 +176,9 @@ class Resolver { const hasteModule = this.getModule(nativeName); if (hasteModule) { const resolvedPath = { + id: `haste:${hasteModule}?${query}`, path: hasteModule, - id: `haste:${hasteModule}?${query}` - } + }; this._moduleNameCache.set(key, resolvedPath); return resolvedPath; } @@ -206,7 +206,10 @@ class Resolver { if (!skipResolution) { // @ts-ignore: the "pnp" version named isn't in DefinitelyTyped - const nodeModule = resolveNodeModule(moduleName, Boolean(process.versions.pnp)); + const nodeModule = resolveNodeModule( + moduleName, + Boolean(process.versions.pnp), + ); if (nodeModule) { this._moduleNameCache.set(key, nodeModule); @@ -220,12 +223,12 @@ class Resolver { const hastePackage = this.getPackage(parts.shift()!); if (hastePackage) { const requireResolve = (name: string) => { - const path = require.resolve(name) + const path = require.resolve(name); return { + id: `haste:${path}?${query}`, path, - id: `haste:${path}?${query}` - } - } + }; + }; try { const hastePackageModule = path.join.apply( path, @@ -234,7 +237,8 @@ class Resolver { // try resolving with custom resolver first to support extensions, // then fallback to require.resolve const resolvedModule = - resolveNodeModule(hastePackageModule) || requireResolve(hastePackageModule); + resolveNodeModule(hastePackageModule) || + requireResolve(hastePackageModule); this._moduleNameCache.set(key, resolvedModule); return resolvedModule; } catch (ignoredError) {} @@ -454,28 +458,27 @@ class Resolver { for (const possibleModuleName of possibleModuleNames) { const updatedName = mapModuleName(possibleModuleName); - const hasteModule = this.getModule(updatedName) + const hasteModule = this.getModule(updatedName); if (hasteModule) { module = { + id: `haste:${hasteModule}?${query}`, path: hasteModule, - id: `haste:${hasteModule}?${query}` - } - break + }; + break; } - const nodeModule = - Resolver.findNodeModule(updatedName, { - basedir: dirname, - browser: this._options.browser, - extensions, - moduleDirectory, - paths, - resolver, - rootDir: this._options.rootDir, - }); + const nodeModule = Resolver.findNodeModule(updatedName, { + basedir: dirname, + browser: this._options.browser, + extensions, + moduleDirectory, + paths, + resolver, + rootDir: this._options.rootDir, + }); if (nodeModule) { - module = nodeModule + module = nodeModule; break; } } diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index ee8728ae4bec..d7849b45cf30 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -939,7 +939,7 @@ class Runtime { filename, id: filename, loaded: false, - rpth: {id: 'InitialModule', path: filename} + rpth: {id: 'InitialModule', path: filename}, }); };