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

fix(testing): resolve jest package from the project root in plugin #27342

Merged
merged 1 commit into from
Aug 8, 2024
Merged
Changes from all commits
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
44 changes: 37 additions & 7 deletions packages/jest/src/plugins/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof import('jest-runtime')>(
'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);
Expand Down Expand Up @@ -403,3 +405,31 @@ function normalizeOptions(options: JestPluginOptions): JestPluginOptions {
options.targetName ??= 'test';
return options;
}

let resolvedJestPaths: Record<string, string>;
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<T>(
packageName: string,
projectRoot: string,
context: CreateNodesContext
): T {
const jestPath = resolveJestPath(projectRoot, context);

return require(require.resolve(packageName, { paths: [dirname(jestPath)] }));
}