Skip to content

Commit

Permalink
feat(testing): allow usage of jest 30 pre-release versions (#27334)
Browse files Browse the repository at this point in the history
Allow usage of Jest v30 pre-release version in preparation for the
upcoming stable release.

Note that this PR is not intended to change any current generator for
creating/setting up projects with Jest 30. That will be done when Jest
v30 becomes stable.

<!-- Please make sure you have read the submission guidelines before
posting an PR -->
<!--
https://github.com/nrwl/nx/blob/master/CONTRIBUTING.md#-submitting-a-pr
-->

<!-- Please make sure that your commit message follows our format -->
<!-- Example: `fix(nx): must begin with lowercase` -->

<!-- If this is a particularly complex change or feature addition, you
can request a dedicated Nx release for this pull request branch. Mention
someone from the Nx team or the `@nrwl/nx-pipelines-reviewers` and they
will confirm if the PR warrants its own release for testing purposes,
and generate it for you if appropriate. -->

## Current Behavior
<!-- This is the behavior we have today -->

## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->
<!-- Fixes NXP-860 -->

Fixes #
  • Loading branch information
leosvelperez committed Aug 9, 2024
1 parent f3ee14b commit 6c0e70e
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 32 deletions.
1 change: 1 addition & 0 deletions packages/jest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"jest-util": "^29.4.1",
"minimatch": "9.0.3",
"resolve.exports": "1.1.0",
"semver": "^7.5.3",
"tslib": "^2.3.0",
"yargs-parser": "21.1.1"
},
Expand Down
14 changes: 2 additions & 12 deletions packages/jest/plugins/resolver.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
import { dirname, extname, join, resolve } from 'path';
import { resolve as resolveExports } from 'resolve.exports';
import type defaultResolver from 'jest-resolve/build/defaultResolver';

interface ResolveOptions {
rootDir: string;
basedir: string;
paths: string[];
moduleDirectory: string[];
browser: boolean;
extensions: string[];
defaultResolver: typeof defaultResolver;
}
import type { ResolverOptions } from 'jest-resolve';

let compilerSetup;
let ts;
Expand Down Expand Up @@ -38,7 +28,7 @@ function getCompilerSetup(rootDir: string) {
return { compilerOptions, host };
}

module.exports = function (path: string, options: ResolveOptions) {
module.exports = function (path: string, options: ResolverOptions) {
const ext = extname(path);
if (ext === '.css' || ext === '.scss' || ext === '.sass' || ext === '.less') {
return require.resolve('identity-obj-proxy');
Expand Down
53 changes: 33 additions & 20 deletions packages/jest/src/plugins/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Config } from '@jest/types';
import {
CreateNodes,
CreateNodesContext,
Expand All @@ -13,22 +14,20 @@ import {
TargetConfiguration,
writeJsonFile,
} from '@nx/devkit';
import { dirname, isAbsolute, join, relative, resolve } from 'path';

import { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';
import { existsSync, readdirSync, readFileSync } from 'fs';
import { readConfig, replaceRootDirInPath } from 'jest-config';
import jestResolve from 'jest-resolve';
import { workspaceDataDirectory } from 'nx/src/utils/cache-directory';
import { calculateHashForCreateNodes } from '@nx/devkit/src/utils/calculate-hash-for-create-nodes';
import {
clearRequireCache,
loadConfigFile,
} from '@nx/devkit/src/utils/config-utils';
import { getGlobPatternsFromPackageManagerWorkspaces } from 'nx/src/plugins/package-json';
import { combineGlobPatterns } from 'nx/src/utils/globs';
import { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';
import { existsSync, readdirSync, readFileSync } from 'fs';
import { minimatch } from 'minimatch';
import { hashObject } from 'nx/src/devkit-internals';
import { getGlobPatternsFromPackageManagerWorkspaces } from 'nx/src/plugins/package-json';
import { workspaceDataDirectory } from 'nx/src/utils/cache-directory';
import { combineGlobPatterns } from 'nx/src/utils/globs';
import { dirname, isAbsolute, join, relative, resolve } from 'path';
import { getInstalledJestMajorVersion } from '../utils/version-utils';

const pmc = getPackageManagerCommand();

Expand Down Expand Up @@ -167,6 +166,12 @@ async function buildJestTargets(
}

const rawConfig = await loadConfigFile(absConfigFilePath);

const { readConfig } = requireJestUtil<typeof import('jest-config')>(
'jest-config',
projectRoot,
context.workspaceRoot
);
const config = await readConfig(
{
_: [],
Expand Down Expand Up @@ -215,7 +220,7 @@ async function buildJestTargets(
const { default: Runtime } = requireJestUtil<typeof import('jest-runtime')>(
'jest-runtime',
projectRoot,
context
context.workspaceRoot
);

const jestContext = await Runtime.createContext(config.projectConfig, {
Expand All @@ -225,11 +230,16 @@ async function buildJestTargets(

const jest = require(resolveJestPath(
projectRoot,
context
context.workspaceRoot
)) as typeof import('jest');
const source = new jest.SearchSource(jestContext);

const specs = await source.getTestPaths(config.globalConfig);
const jestVersion = getInstalledJestMajorVersion()!;
const specs =
jestVersion >= 30
? // @ts-expect-error Jest 30+ expects the project config as the second argument
await source.getTestPaths(config.globalConfig, config.projectConfig)
: await source.getTestPaths(config.globalConfig);

const testPaths = new Set(specs.tests.map(({ path }) => path));

Expand Down Expand Up @@ -345,11 +355,17 @@ function resolvePresetInput(
return null;
}

const { replaceRootDirInPath } = requireJestUtil<
typeof import('jest-config')
>('jest-config', projectRoot, workspaceRoot);
let presetPath = replaceRootDirInPath(projectRoot, presetValue);
const isNpmPackage = !presetValue.startsWith('.') && !isAbsolute(presetPath);
presetPath = presetPath.startsWith('.')
? presetPath
: join(presetPath, 'jest-preset');
const { default: jestResolve } = requireJestUtil<
typeof import('jest-resolve')
>('jest-resolve', projectRoot, workspaceRoot);
const presetModule = jestResolve.findNodeModule(presetPath, {
basedir: projectRoot,
extensions: ['.json', '.js', '.cjs', '.mjs'],
Expand All @@ -371,7 +387,7 @@ function resolvePresetInput(

function getOutputs(
projectRoot: string,
{ globalConfig }: Awaited<ReturnType<typeof readConfig>>,
{ globalConfig }: { globalConfig: Config.GlobalConfig },
context: CreateNodesContext
): string[] {
function getOutput(path: string): string {
Expand Down Expand Up @@ -407,17 +423,14 @@ function normalizeOptions(options: JestPluginOptions): JestPluginOptions {
}

let resolvedJestPaths: Record<string, string>;
function resolveJestPath(
projectRoot: string,
context: CreateNodesContext
): string {
function resolveJestPath(projectRoot: string, workspaceRoot: string): string {
resolvedJestPaths ??= {};
if (resolvedJestPaths[projectRoot]) {
return resolvedJestPaths[projectRoot];
}

return require.resolve('jest', {
paths: [projectRoot, context.workspaceRoot, __dirname],
paths: [projectRoot, workspaceRoot, __dirname],
});
}

Expand All @@ -427,9 +440,9 @@ function resolveJestPath(
function requireJestUtil<T>(
packageName: string,
projectRoot: string,
context: CreateNodesContext
workspaceRoot: string
): T {
const jestPath = resolveJestPath(projectRoot, context);
const jestPath = resolveJestPath(projectRoot, workspaceRoot);

return require(require.resolve(packageName, { paths: [dirname(jestPath)] }));
}
15 changes: 15 additions & 0 deletions packages/jest/src/utils/version-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { major } from 'semver';

export function getInstalledJestVersion(): string | null {
try {
return require('jest/package.json').version;
} catch {
return null;
}
}

export function getInstalledJestMajorVersion(): number | null {
const installedVersion = getInstalledJestVersion();

return installedVersion ? major(installedVersion) : null;
}

0 comments on commit 6c0e70e

Please sign in to comment.