@nx/jest 24.1.0-beta.2 → 24.1.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,19 +9,22 @@ const plugin_1 = require("../../plugins/plugin");
9
9
  const config_file_1 = require("../../utils/config/config-file");
10
10
  const assert_supported_jest_version_1 = require("../../utils/assert-supported-jest-version");
11
11
  const versions_1 = require("../../utils/versions");
12
+ const rewrite_uninferred_targets_1 = require("./lib/rewrite-uninferred-targets");
12
13
  async function convertToInferred(tree, options) {
13
14
  (0, assert_supported_jest_version_1.assertSupportedJestVersion)(tree);
14
15
  const projectGraph = await (0, devkit_1.createProjectGraphAsync)();
15
- const migratedProjects = await (0, internal_1.migrateProjectExecutorsToPlugin)(tree, projectGraph, '@nx/jest/plugin', plugin_1.createNodesV2, { targetName: 'test' }, [
16
- {
17
- executors: ['@nx/jest:jest', '@nrwl/jest:jest'],
18
- postTargetTransformer,
19
- targetPluginOptionMapper: (targetName) => ({ targetName }),
20
- },
21
- ], options.project);
22
- if (migratedProjects.size === 0) {
23
- throw new internal_1.NoTargetsToMigrateError();
24
- }
16
+ await (0, internal_1.convertWithUninferredTargetsRewritten)(tree, rewrite_uninferred_targets_1.jestConfigRewrite, async () => {
17
+ const migratedProjects = await (0, internal_1.migrateProjectExecutorsToPlugin)(tree, projectGraph, '@nx/jest/plugin', plugin_1.createNodesV2, { targetName: 'test' }, [
18
+ {
19
+ executors: rewrite_uninferred_targets_1.jestConfigRewrite.executors,
20
+ postTargetTransformer,
21
+ targetPluginOptionMapper: (targetName) => ({ targetName }),
22
+ },
23
+ ], options.project);
24
+ if (migratedProjects.size === 0) {
25
+ throw new internal_1.NoTargetsToMigrateError();
26
+ }
27
+ }, options.project);
25
28
  if (!options.skipFormat) {
26
29
  await (0, devkit_1.formatFiles)(tree);
27
30
  }
@@ -0,0 +1,6 @@
1
+ import { type UninferredTargetRewrite } from '@nx/devkit/internal';
2
+ /**
3
+ * @nx/jest/plugin infers a project's target only from `jest.config.<ext>` in
4
+ * its root, so a target running another config becomes an explicit command.
5
+ */
6
+ export declare const jestConfigRewrite: UninferredTargetRewrite;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.jestConfigRewrite = void 0;
4
+ const internal_1 = require("@nx/devkit/internal");
5
+ const node_path_1 = require("node:path");
6
+ const config_file_1 = require("../../../utils/config/config-file");
7
+ const executors = ['@nx/jest:jest', '@nrwl/jest:jest'];
8
+ // The removed executor set this on every run; @nx/jest/plugin sets the same value
9
+ const tsNodeCompilerOptions = JSON.stringify({
10
+ moduleResolution: 'node10',
11
+ module: 'commonjs',
12
+ customConditions: null,
13
+ });
14
+ const isBoolean = (value) => typeof value === 'boolean';
15
+ const isPositiveInteger = (value) => Number.isSafeInteger(value) && value > 0;
16
+ /**
17
+ * The only options a rewritten target may set. Generators wrote jestConfig,
18
+ * tsConfig, passWithNoTests, ci and codeCoverage. Jest 29 and 30 read the other
19
+ * flags from --name=value as the values the executor passed to runCLI.
20
+ */
21
+ const acceptedOptions = new Map([
22
+ ['jestConfig', internal_1.isPlainPath],
23
+ ['tsConfig', (value) => typeof value === 'string'],
24
+ ['codeCoverage', isBoolean],
25
+ ['bail', isBoolean],
26
+ ['ci', isBoolean],
27
+ ['detectOpenHandles', isBoolean],
28
+ ['forceExit', isBoolean],
29
+ ['logHeapUsage', isBoolean],
30
+ ['passWithNoTests', isBoolean],
31
+ ['runInBand', isBoolean],
32
+ ['silent', isBoolean],
33
+ ['maxWorkers', isPositiveInteger],
34
+ ['testTimeout', isPositiveInteger],
35
+ ]);
36
+ /**
37
+ * @nx/jest/plugin infers a project's target only from `jest.config.<ext>` in
38
+ * its root, so a target running another config becomes an explicit command.
39
+ */
40
+ exports.jestConfigRewrite = {
41
+ executors,
42
+ tool: 'Jest',
43
+ isInferred: (_tree, target, project) => {
44
+ const jestConfig = target.options?.jestConfig;
45
+ return !jestConfig || isProjectRootJestConfig(jestConfig, project.root);
46
+ },
47
+ toRunCommandsTarget,
48
+ };
49
+ function isProjectRootJestConfig(jestConfig, projectRoot) {
50
+ const path = node_path_1.posix.normalize(jestConfig);
51
+ return config_file_1.jestConfigExtensions.some((ext) => path === node_path_1.posix.join(projectRoot, `jest.config.${ext}`));
52
+ }
53
+ // jestConfig becomes the command, and the executor never passed tsConfig to Jest
54
+ function toJestOptions({ jestConfig: _jestConfig, tsConfig: _tsConfig, codeCoverage, ...flags }) {
55
+ return codeCoverage === undefined
56
+ ? flags
57
+ : { ...flags, coverage: codeCoverage };
58
+ }
59
+ // The leading ./ is what the move generator rewrites for a root project
60
+ function jestCommand(jestConfig) {
61
+ return `jest --config ${(0, internal_1.toProjectRelativePath)(node_path_1.posix.normalize(jestConfig), '.')}`;
62
+ }
63
+ function toRunCommandsTarget(target) {
64
+ const { executor: _executor, options, configurations, ...rest } = target;
65
+ const configurationNames = Object.keys(configurations ?? {});
66
+ for (const values of [options, ...Object.values(configurations ?? {})]) {
67
+ (0, internal_1.assertAcceptedOptions)(values, acceptedOptions);
68
+ }
69
+ for (const name of [undefined, ...configurationNames]) {
70
+ const values = (0, internal_1.optionsFor)(target, name);
71
+ // runCLI accepted this pair, but Jest's CLI rejects it
72
+ if (values.runInBand === true && 'maxWorkers' in values) {
73
+ throw new Error('Jest rejects runInBand with maxWorkers on its CLI.');
74
+ }
75
+ }
76
+ const rewritten = {
77
+ executor: 'nx:run-commands',
78
+ ...rest,
79
+ options: {
80
+ command: jestCommand(options.jestConfig),
81
+ // The executor ran from where nx started, usually the workspace root.
82
+ // Set explicitly, so an nx:run-commands default's cwd can't apply.
83
+ cwd: '.',
84
+ env: { TS_NODE_COMPILER_OPTIONS: tsNodeCompilerOptions },
85
+ ...toJestOptions(options),
86
+ },
87
+ };
88
+ if (configurations) {
89
+ rewritten.configurations = Object.fromEntries(configurationNames.map((name) => {
90
+ const { jestConfig } = configurations[name];
91
+ return [
92
+ name,
93
+ {
94
+ ...(jestConfig ? { command: jestCommand(jestConfig) } : {}),
95
+ ...toJestOptions(configurations[name]),
96
+ },
97
+ ];
98
+ }));
99
+ }
100
+ (0, internal_1.assertOutputOptionsKept)(target, rewritten);
101
+ return rewritten;
102
+ }
@@ -1,4 +1,4 @@
1
- import { type Tree } from '@nx/devkit';
1
+ import type { Tree } from '@nx/devkit';
2
2
  export default function update(tree: Tree): Promise<{
3
3
  nextSteps?: string[];
4
4
  agentContext?: string[];
@@ -1,225 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = update;
4
- const devkit_1 = require("@nx/devkit");
5
4
  const internal_1 = require("@nx/devkit/internal");
6
- const node_path_1 = require("node:path");
7
- const node_util_1 = require("node:util");
8
- const config_file_1 = require("../../utils/config/config-file");
9
- const removedExecutors = ['@nx/jest:jest', '@nrwl/jest:jest'];
10
- // The removed executor set this on every run; @nx/jest/plugin sets the same value
11
- const tsNodeCompilerOptions = JSON.stringify({
12
- moduleResolution: 'node10',
13
- module: 'commonjs',
14
- customConditions: null,
15
- });
16
- const isBoolean = (value) => typeof value === 'boolean';
17
- const isPositiveInteger = (value) => Number.isSafeInteger(value) && value > 0;
18
- /**
19
- * The only options a rewritten target may set. Generators wrote jestConfig,
20
- * tsConfig, passWithNoTests, ci and codeCoverage. Jest 29 and 30 read the other
21
- * flags from --name=value as the values the executor passed to runCLI.
22
- */
23
- const acceptedOptions = new Map([
24
- ['jestConfig', isPlainPath],
25
- ['tsConfig', (value) => typeof value === 'string'],
26
- ['codeCoverage', isBoolean],
27
- ['bail', isBoolean],
28
- ['ci', isBoolean],
29
- ['detectOpenHandles', isBoolean],
30
- ['forceExit', isBoolean],
31
- ['logHeapUsage', isBoolean],
32
- ['passWithNoTests', isBoolean],
33
- ['runInBand', isBoolean],
34
- ['silent', isBoolean],
35
- ['maxWorkers', isPositiveInteger],
36
- ['testTimeout', isPositiveInteger],
37
- ]);
38
5
  function update(tree) {
39
- return (0, internal_1.migrateRemovedExecutors)(tree, removedExecutors, async (tree, options) => {
40
- const converter = require('../../generators/convert-to-inferred/convert-to-inferred');
41
- const unconverted = rewriteTargetsWithUndetectedConfig(tree);
42
- try {
43
- return await converter.convertToInferred(tree, options);
44
- }
45
- finally {
46
- restoreTargets(tree, unconverted);
47
- }
6
+ return (0, internal_1.migrateRemovedExecutors)(tree, ['@nx/jest:jest', '@nrwl/jest:jest'], async (tree, options) => {
7
+ const { convertToInferred } = require('../../generators/convert-to-inferred/convert-to-inferred');
8
+ return convertToInferred(tree, options);
48
9
  });
49
10
  }
50
- /**
51
- * @nx/jest/plugin infers a project's target only from `jest.config.<ext>` in
52
- * its root, so a target running another config becomes an explicit command.
53
- * A target that can't be rewritten is removed and returned, because the
54
- * converter would switch it to the project's `jest.config.<ext>`.
55
- */
56
- function rewriteTargetsWithUndetectedConfig(tree) {
57
- const targetDefaults = (0, devkit_1.readNxJson)(tree)?.targetDefaults;
58
- const unconvertedByProject = new Map();
59
- for (const [projectName, project] of (0, devkit_1.getProjects)(tree)) {
60
- const unconverted = {};
61
- let changed = false;
62
- for (const [targetName, target] of Object.entries(project.targets ?? {})) {
63
- if (!removedExecutors.includes(target.executor)) {
64
- continue;
65
- }
66
- const readDefaults = (executor) => (0, internal_1.readTargetDefaultsForTarget)(targetName, targetDefaults, executor, {
67
- projectName,
68
- projectNode: { name: projectName, type: 'lib', data: project },
69
- });
70
- let runsUndetectedConfig = false;
71
- try {
72
- const executorDefaults = readDefaults(target.executor);
73
- const resolved = resolveTarget(target, executorDefaults, project, `${projectName}:${targetName}`);
74
- const jestConfig = resolved.options?.jestConfig;
75
- if (!jestConfig || isProjectRootJestConfig(jestConfig, project.root)) {
76
- continue;
77
- }
78
- runsUndetectedConfig = true;
79
- const rewritten = toRunCommandsTarget(resolved);
80
- assertDefaultsKeepTarget(rewritten, executorDefaults, readDefaults('nx:run-commands'));
81
- project.targets[targetName] = rewritten;
82
- changed = true;
83
- }
84
- catch (error) {
85
- devkit_1.logger.warn(`Could not rewrite target "${targetName}" in project "${projectName}" to run Jest with its config file: ${String(error)}`);
86
- if (runsUndetectedConfig) {
87
- unconverted[targetName] = target;
88
- delete project.targets[targetName];
89
- changed = true;
90
- }
91
- }
92
- }
93
- if (changed) {
94
- (0, devkit_1.updateProjectConfiguration)(tree, projectName, project);
95
- }
96
- if (Object.keys(unconverted).length) {
97
- unconvertedByProject.set(projectName, unconverted);
98
- }
99
- }
100
- return unconvertedByProject;
101
- }
102
- function restoreTargets(tree, targetsByProject) {
103
- for (const [projectName, targets] of targetsByProject) {
104
- // Read again to keep what the converter did to sibling targets
105
- const project = (0, devkit_1.readProjectConfiguration)(tree, projectName);
106
- project.targets = { ...project.targets, ...targets };
107
- (0, devkit_1.updateProjectConfiguration)(tree, projectName, project);
108
- }
109
- }
110
- /**
111
- * The target merged with the defaults the removed executor received, with Nx
112
- * tokens resolved.
113
- */
114
- function resolveTarget(target, defaults, project, key) {
115
- const resolved = (0, internal_1.mergeTargetConfigurations)(structuredClone(target), structuredClone(defaults ?? {}));
116
- if (resolved.options) {
117
- resolved.options = (0, internal_1.resolveNxTokensInOptions)(resolved.options, project, key);
118
- }
119
- for (const name of Object.keys(resolved.configurations ?? {})) {
120
- resolved.configurations[name] = (0, internal_1.resolveNxTokensInOptions)(resolved.configurations[name], project, `${key}:${name}`);
121
- }
122
- return resolved;
123
- }
124
- /**
125
- * Target defaults are matched by executor, so the rewritten target can get
126
- * entries the removed executor never did. They must not change it.
127
- */
128
- function assertDefaultsKeepTarget(target, executorDefaults, runCommandsDefaults) {
129
- if (!runCommandsDefaults) {
130
- return;
131
- }
132
- // The executor got these entries too, and the target holds their values
133
- // translated for Jest
134
- if ((0, node_util_1.isDeepStrictEqual)(executorDefaults, runCommandsDefaults)) {
135
- return;
136
- }
137
- if (!(0, node_util_1.isDeepStrictEqual)(withDefaults(target, runCommandsDefaults), withDefaults(target, {}))) {
138
- throw new Error('The target defaults that apply to nx:run-commands targets would change it.');
139
- }
140
- }
141
- // Resolves '...' spreads too, and drops the undefined values the merge leaves
142
- function withDefaults(target, defaults) {
143
- return JSON.parse(JSON.stringify((0, internal_1.mergeTargetConfigurations)(structuredClone(target), structuredClone(defaults), undefined, undefined, undefined, false)));
144
- }
145
- function isProjectRootJestConfig(jestConfig, projectRoot) {
146
- const path = node_path_1.posix.normalize(jestConfig);
147
- return config_file_1.jestConfigExtensions.some((ext) => path === node_path_1.posix.join(projectRoot, `jest.config.${ext}`));
148
- }
149
- // Relative, and left unchanged by sh, cmd.exe and nx:run-commands
150
- function isPlainPath(value) {
151
- return typeof value === 'string' && /^[\w@+.-][\w@+./-]*$/.test(value);
152
- }
153
- function assertAcceptedOptions(options) {
154
- for (const [name, value] of Object.entries(options)) {
155
- if (!acceptedOptions.get(name)?.(value)) {
156
- throw new Error(`The rewrite does not accept the "${name}" option set to ${JSON.stringify(value)}.`);
157
- }
158
- }
159
- }
160
- // jestConfig becomes the command, and the executor never passed tsConfig to Jest
161
- function toJestOptions({ jestConfig: _jestConfig, tsConfig: _tsConfig, codeCoverage, ...flags }) {
162
- return codeCoverage === undefined
163
- ? flags
164
- : { ...flags, coverage: codeCoverage };
165
- }
166
- // The leading ./ is what the move generator rewrites for a root project
167
- function jestCommand(jestConfig) {
168
- return `jest --config ${(0, internal_1.toProjectRelativePath)(node_path_1.posix.normalize(jestConfig), '.')}`;
169
- }
170
- function optionsFor(target, configuration) {
171
- return {
172
- ...target.options,
173
- ...(configuration ? target.configurations[configuration] : {}),
174
- };
175
- }
176
- function toRunCommandsTarget(target) {
177
- const { executor: _executor, options, configurations, ...rest } = target;
178
- const configurationNames = Object.keys(configurations ?? {});
179
- for (const values of [options, ...Object.values(configurations ?? {})]) {
180
- assertAcceptedOptions(values);
181
- }
182
- for (const name of [undefined, ...configurationNames]) {
183
- const values = optionsFor(target, name);
184
- // runCLI accepted this pair, but Jest's CLI rejects it
185
- if (values.runInBand === true && 'maxWorkers' in values) {
186
- throw new Error('Jest rejects runInBand with maxWorkers on its CLI.');
187
- }
188
- }
189
- const rewritten = {
190
- executor: 'nx:run-commands',
191
- ...rest,
192
- options: {
193
- command: jestCommand(options.jestConfig),
194
- // The executor ran from where nx started, usually the workspace root.
195
- // Set explicitly, so an nx:run-commands default's cwd can't apply.
196
- cwd: '.',
197
- env: { TS_NODE_COMPILER_OPTIONS: tsNodeCompilerOptions },
198
- ...toJestOptions(options),
199
- },
200
- };
201
- if (configurations) {
202
- rewritten.configurations = Object.fromEntries(configurationNames.map((name) => {
203
- const { jestConfig } = configurations[name];
204
- return [
205
- name,
206
- {
207
- ...(jestConfig ? { command: jestCommand(jestConfig) } : {}),
208
- ...toJestOptions(configurations[name]),
209
- },
210
- ];
211
- }));
212
- }
213
- const outputOptions = [
214
- ...(rest.outputs ?? []).join(' ').matchAll(/\{options\.(\w+)/g),
215
- ].map(([, name]) => name);
216
- for (const name of [undefined, ...configurationNames]) {
217
- const before = optionsFor(target, name);
218
- const after = optionsFor(rewritten, name);
219
- const changed = outputOptions.find((option) => !(0, node_util_1.isDeepStrictEqual)(before[option], after[option]));
220
- if (changed) {
221
- throw new Error(`An output reads the "${changed}" option, which the rewrite changes.`);
222
- }
223
- }
224
- return rewritten;
225
- }
@@ -2,7 +2,7 @@
2
2
 
3
3
  Nx 24 removes the `@nx/jest:jest` executor and its `@nrwl/jest:jest` alias. The migration registers `@nx/jest/plugin` in `nx.json` and converts the targets that use those executors to inferred tasks. Options the plugin does not infer stay on the target. A target with nothing left to override is removed from project configuration. When several projects share the same remaining options, those options move to a `targetDefaults` entry scoped to the plugin. `targetDefaults` entries keyed by a removed executor are removed once no target uses that executor.
4
4
 
5
- The plugin only infers a target from `jest.config.<ext>` in the project root. A target that runs any other config file, such as a root project's `jest.config.app.ts`, becomes an `nx:run-commands` target that runs `jest --config <file>` from the workspace root. It keeps the options, configurations and target defaults it used. The executor ran Jest from the directory `nx` started in, so a run started from another directory now uses the workspace root too.
5
+ The plugin only infers a target from `jest.config.<ext>` in the project root. A target that runs any other config file, such as a root project's `jest.config.app.ts`, becomes an `nx:run-commands` target that runs `jest --config <file>` from the workspace root. It keeps the options, configurations and target defaults it used. The executor ran Jest from the directory `nx` started in, so a run started from another directory now uses the workspace root too. Running `nx g @nx/jest:convert-to-inferred` by hand applies the same rewrite.
6
6
 
7
7
  The rewrite accepts only these options, in the target and in each configuration:
8
8
 
@@ -16,7 +16,7 @@ The target keeps the removed executor, and the migration lists it, in these case
16
16
  - It sets any other option, or sets an accepted option to another kind of value.
17
17
  - It sets `runInBand: true` together with `maxWorkers`, also through a configuration. Jest's CLI rejects that pair.
18
18
  - An output reads an option the rewrite removes or renames, such as `{options.tsConfig}`.
19
- - `targetDefaults` that apply to `nx:run-commands` targets would change it.
19
+ - `targetDefaults` that apply to `nx:run-commands` targets would change it. An entry keyed by the target name applies to both executors, so it holds the target back when it sets an option the rewrite renames.
20
20
 
21
21
  The migration lists the targets the converter cannot convert safely. In agentic runs, an AI prompt finishes them and validates the project graph.
22
22
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/jest",
3
- "version": "24.1.0-beta.2",
3
+ "version": "24.1.0-beta.3",
4
4
  "private": false,
5
5
  "type": "commonjs",
6
6
  "files": [
@@ -92,7 +92,8 @@
92
92
  },
93
93
  "peerDependencies": {
94
94
  "jest": "^29.0.0 || ^30.0.0",
95
- "ts-jest": "^29.0.0"
95
+ "ts-jest": "^29.0.0",
96
+ "typescript": "^5.8.0 || ^6.0.0"
96
97
  },
97
98
  "peerDependenciesMeta": {
98
99
  "jest": {
@@ -100,11 +101,14 @@
100
101
  },
101
102
  "ts-jest": {
102
103
  "optional": true
104
+ },
105
+ "typescript": {
106
+ "optional": true
103
107
  }
104
108
  },
105
109
  "dependencies": {
106
- "@nx/devkit": "24.1.0-beta.2",
107
- "@nx/js": "24.1.0-beta.2",
110
+ "@nx/devkit": "24.1.0-beta.3",
111
+ "@nx/js": "24.1.0-beta.3",
108
112
  "@phenomnomnominal/tsquery": "~6.2.0",
109
113
  "identity-obj-proxy": "3.0.0",
110
114
  "jest-config": "^30.0.2",
@@ -118,7 +122,7 @@
118
122
  "yargs-parser": "21.1.1"
119
123
  },
120
124
  "devDependencies": {
121
- "nx": "24.1.0-beta.2"
125
+ "nx": "24.1.0-beta.3"
122
126
  },
123
127
  "publishConfig": {
124
128
  "access": "public"