From 46dcee6dd25174b050206925c979e1408a6d8641 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leosvel=20P=C3=A9rez=20Espinosa?= Date: Thu, 8 Aug 2024 17:37:06 +0200 Subject: [PATCH] fix(testing): resolve jest package from the project root in plugin (#27342) ## Current Behavior ## Expected Behavior ## Related Issue(s) Fixes # --- packages/jest/src/plugins/plugin.ts | 44 ++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/packages/jest/src/plugins/plugin.ts b/packages/jest/src/plugins/plugin.ts index e82eb2114de25..91569f2d37b18 100644 --- a/packages/jest/src/plugins/plugin.ts +++ b/packages/jest/src/plugins/plugin.ts @@ -211,20 +211,22 @@ async function buildJestTargets( let metadata: ProjectConfiguration['metadata']; if (options?.ciTargetName) { - // Resolve the version of `jest-runtime` that `jest` is using. - const jestPath = require.resolve('jest'); - const jest = require(jestPath) as typeof import('jest'); // nx-ignore-next-line - const { default: Runtime } = require(require.resolve('jest-runtime', { - paths: [dirname(jestPath)], - // nx-ignore-next-line - })) as typeof import('jest-runtime'); + const { default: Runtime } = requireJestUtil( + 'jest-runtime', + projectRoot, + context + ); const jestContext = await Runtime.createContext(config.projectConfig, { maxWorkers: 1, watchman: false, }); + const jest = require(resolveJestPath( + projectRoot, + context + )) as typeof import('jest'); const source = new jest.SearchSource(jestContext); const specs = await source.getTestPaths(config.globalConfig); @@ -403,3 +405,31 @@ function normalizeOptions(options: JestPluginOptions): JestPluginOptions { options.targetName ??= 'test'; return options; } + +let resolvedJestPaths: Record; +function resolveJestPath( + projectRoot: string, + context: CreateNodesContext +): string { + resolvedJestPaths ??= {}; + if (resolvedJestPaths[projectRoot]) { + return resolvedJestPaths[projectRoot]; + } + + return require.resolve('jest', { + paths: [projectRoot, context.workspaceRoot, __dirname], + }); +} + +/** + * Resolves a jest util package version that `jest` is using. + */ +function requireJestUtil( + packageName: string, + projectRoot: string, + context: CreateNodesContext +): T { + const jestPath = resolveJestPath(projectRoot, context); + + return require(require.resolve(packageName, { paths: [dirname(jestPath)] })); +}