From 17f09bc1d6f8e782546f5f5151a0f33d72596a0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leosvel=20P=C3=A9rez=20Espinosa?= Date: Wed, 14 Aug 2024 16:48:43 +0200 Subject: [PATCH] fix(testing): resolve jest utils in plugin from the @jest/core package location that jest uses (#27422) ## Current Behavior In the `@nx/jest/plugin` some jest utils are imported from the location of the `jest` package to ensure the plugin uses the same utils the `jest` package would use. This is not entirely correct because the `jest` package doesn't directly depend on those utils, so they might not be resolved correctly. ## Expected Behavior The `@nx/jest/plugin` should import those jest utils from the location of the `@jest/core` package resolved from the `jest` package location, to ensure the plugin uses the same utils the `jest` package would use. ## Related Issue(s) Fixes # --- packages/jest/src/plugins/plugin.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/jest/src/plugins/plugin.ts b/packages/jest/src/plugins/plugin.ts index fdcb33388b..4311cd2ae2 100644 --- a/packages/jest/src/plugins/plugin.ts +++ b/packages/jest/src/plugins/plugin.ts @@ -436,6 +436,7 @@ function resolveJestPath(projectRoot: string, workspaceRoot: string): string { return resolvedJestPaths[projectRoot]; } +let resolvedJestCorePaths: Record; /** * Resolves a jest util package version that `jest` is using. */ @@ -446,5 +447,15 @@ function requireJestUtil( ): T { const jestPath = resolveJestPath(projectRoot, workspaceRoot); - return require(require.resolve(packageName, { paths: [dirname(jestPath)] })); + resolvedJestCorePaths ??= {}; + if (!resolvedJestCorePaths[jestPath]) { + // nx-ignore-next-line + resolvedJestCorePaths[jestPath] = require.resolve('@jest/core', { + paths: [dirname(jestPath)], + }); + } + + return require(require.resolve(packageName, { + paths: [dirname(resolvedJestCorePaths[jestPath])], + })); }