@nx/jest 16.10.0 → 17.0.0-beta.1

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.
Files changed (25) hide show
  1. package/migrations.json +0 -199
  2. package/package.json +4 -4
  3. package/src/generators/configuration/lib/update-workspace.js +0 -11
  4. package/src/migrations/update-12-1-2/update-jest-preset-angular.d.ts +0 -1
  5. package/src/migrations/update-12-1-2/update-jest-preset-angular.js +0 -51
  6. package/src/migrations/update-12-1-2/update-ts-jest.d.ts +0 -2
  7. package/src/migrations/update-12-1-2/update-ts-jest.js +0 -31
  8. package/src/migrations/update-12-4-0/add-test-environment-for-node.d.ts +0 -2
  9. package/src/migrations/update-12-4-0/add-test-environment-for-node.js +0 -34
  10. package/src/migrations/update-12-4-0/update-jest-preset-angular.d.ts +0 -25
  11. package/src/migrations/update-12-4-0/update-jest-preset-angular.js +0 -82
  12. package/src/migrations/update-12-6-0/update-base-jest-config.d.ts +0 -2
  13. package/src/migrations/update-12-6-0/update-base-jest-config.js +0 -38
  14. package/src/migrations/update-13-1-2/update-tsconfigs-for-tests.d.ts +0 -2
  15. package/src/migrations/update-13-1-2/update-tsconfigs-for-tests.js +0 -56
  16. package/src/migrations/update-13-4-4/add-missing-root-babel-config.d.ts +0 -2
  17. package/src/migrations/update-13-4-4/add-missing-root-babel-config.js +0 -39
  18. package/src/migrations/update-14-0-0/update-jest-config-ext.d.ts +0 -3
  19. package/src/migrations/update-14-0-0/update-jest-config-ext.js +0 -110
  20. package/src/migrations/update-14-1-5/update-exports-jest-config.d.ts +0 -7
  21. package/src/migrations/update-14-1-5/update-exports-jest-config.js +0 -65
  22. package/src/migrations/update-14-6-0/update-configs-jest-28.d.ts +0 -5
  23. package/src/migrations/update-14-6-0/update-configs-jest-28.js +0 -80
  24. package/src/migrations/update-14-6-0/update-tests-jest-28.d.ts +0 -24
  25. package/src/migrations/update-14-6-0/update-tests-jest-28.js +0 -153
package/migrations.json CHANGED
@@ -1,77 +1,5 @@
1
1
  {
2
2
  "generators": {
3
- "update-jest-preset-angular-8-4-0": {
4
- "version": "12.1.0-beta.1",
5
- "cli": "nx",
6
- "description": "Update jest-preset-angular to version 8.4.0",
7
- "factory": "./src/migrations/update-12-1-2/update-jest-preset-angular"
8
- },
9
- "update-ts-jest-6-5-5": {
10
- "version": "12.1.2-beta.1",
11
- "cli": "nx",
12
- "description": "Replace tsConfig with tsconfig for ts-jest in jest.config.js",
13
- "factory": "./src/migrations/update-12-1-2/update-ts-jest"
14
- },
15
- "support-jest-27": {
16
- "version": "12.4.0-beta.1",
17
- "cli": "nx",
18
- "description": "Add testEnvironment: 'jsdom' in web apps + libraries",
19
- "factory": "./src/migrations/update-12-4-0/add-test-environment-for-node"
20
- },
21
- "update-ts-jest-and-jest-preset-angular": {
22
- "version": "12.4.0-beta.1",
23
- "cli": "nx",
24
- "description": "Support for Jest 27 via updating ts-jest + jest-preset-angular",
25
- "factory": "./src/migrations/update-12-4-0/update-jest-preset-angular"
26
- },
27
- "update-jest-config-to-use-util": {
28
- "version": "12.6.0-beta.0",
29
- "cli": "nx",
30
- "description": "Uses `getJestProjects()` to populate projects array in root level `jest.config.js` file.",
31
- "factory": "./src/migrations/update-12-6-0/update-base-jest-config"
32
- },
33
- "update-ts-config-for-test-filenames": {
34
- "version": "13.1.2-beta.0",
35
- "cli": "nx",
36
- "description": "Support .test. file names in tsconfigs",
37
- "factory": "./src/migrations/update-13-1-2/update-tsconfigs-for-tests"
38
- },
39
- "add-missing-root-babel-config": {
40
- "version": "13.4.4-beta.0",
41
- "cli": "nx",
42
- "description": "Create a root babel config file if it doesn't exist and using babel-jest in jest.config.js and add @nrwl/web as needed",
43
- "factory": "./src/migrations/update-13-4-4/add-missing-root-babel-config"
44
- },
45
- "update-jest-config-extensions": {
46
- "version": "14.0.0-beta.2",
47
- "cli": "nx",
48
- "description": "Update move jest config files to .ts files.",
49
- "factory": "./src/migrations/update-14-0-0/update-jest-config-ext"
50
- },
51
- "update-to-export-default": {
52
- "version": "14.1.5-beta.0",
53
- "cli": "nx",
54
- "description": "Update to export default in jest config and revert jest.preset.ts to jest.preset.js",
55
- "factory": "./src/migrations/update-14-1-5/update-exports-jest-config"
56
- },
57
- "exclude-jest-config-from-ts-config": {
58
- "version": "14.5.5-beta.0",
59
- "cli": "nx",
60
- "description": "Exclude jest.config.ts from tsconfig where missing.",
61
- "factory": "./src/migrations/update-14-0-0/update-jest-config-ext"
62
- },
63
- "update-configs-jest-28": {
64
- "version": "14.6.0-beta.0",
65
- "cli": "nx",
66
- "description": "Update jest configs to support jest 28 changes (https://jestjs.io/docs/upgrading-to-jest28#configuration-options)",
67
- "factory": "./src/migrations/update-14-6-0/update-configs-jest-28"
68
- },
69
- "update-tests-jest-28": {
70
- "version": "14.6.0-beta.0",
71
- "cli": "nx",
72
- "description": "Update jest test files to support jest 28 changes (https://jestjs.io/docs/upgrading-to-jest28)",
73
- "factory": "./src/migrations/update-14-6-0/update-tests-jest-28"
74
- },
75
3
  "add-jest-inputs": {
76
4
  "version": "15.0.0-beta.0",
77
5
  "cli": "nx",
@@ -104,133 +32,6 @@
104
32
  }
105
33
  },
106
34
  "packageJsonUpdates": {
107
- "12.1.0": {
108
- "version": "12.1.0-beta.1",
109
- "packages": {
110
- "jest-preset-angular": {
111
- "version": "8.4.0",
112
- "alwaysAddToPackageJson": false
113
- },
114
- "ts-jest": {
115
- "version": "26.5.5",
116
- "alwaysAddToPackageJson": false
117
- }
118
- }
119
- },
120
- "12.4.0": {
121
- "version": "12.4.0-beta.1",
122
- "packages": {
123
- "jest": {
124
- "version": "27.0.3",
125
- "alwaysAddToPackageJson": false
126
- },
127
- "ts-jest": {
128
- "version": "27.0.3",
129
- "alwaysAddToPackageJson": false
130
- },
131
- "jest-preset-angular": {
132
- "version": "9.0.3",
133
- "alwaysAddToPackageJson": false
134
- }
135
- }
136
- },
137
- "12.10.0": {
138
- "version": "12.10.0-beta.1",
139
- "packages": {
140
- "jest": {
141
- "version": "27.2.3",
142
- "alwaysAddToPackageJson": false
143
- },
144
- "@types/jest": {
145
- "version": "27.0.2",
146
- "alwaysAddToPackageJson": false
147
- },
148
- "ts-jest": {
149
- "version": "27.0.5",
150
- "alwaysAddToPackageJson": false
151
- },
152
- "babel-jest": {
153
- "version": "27.2.3",
154
- "alwaysAddToPackageJson": false
155
- }
156
- }
157
- },
158
- "14.0.0": {
159
- "version": "14.0.0-beta.2",
160
- "packages": {
161
- "jest": {
162
- "version": "27.5.1",
163
- "alwaysAddToPackageJson": false
164
- },
165
- "@types/jest": {
166
- "version": "27.4.1",
167
- "alwaysAddToPackageJson": false
168
- },
169
- "ts-jest": {
170
- "version": "27.1.4",
171
- "alwaysAddToPackageJson": false
172
- },
173
- "babel-jest": {
174
- "version": "27.5.1",
175
- "alwaysAddToPackageJson": false
176
- }
177
- }
178
- },
179
- "14.2.0": {
180
- "version": "14.2.0-rc.2",
181
- "packages": {
182
- "ts-node": {
183
- "version": "~10.8.0",
184
- "alwaysAddToPackageJson": false
185
- }
186
- }
187
- },
188
- "14.5.5": {
189
- "version": "14.5.5-beta.0",
190
- "packages": {
191
- "ts-node": {
192
- "version": "10.9.1",
193
- "alwaysAddToPackageJson": false
194
- }
195
- }
196
- },
197
- "14.6.0": {
198
- "version": "14.6.0-beta.0",
199
- "packages": {
200
- "jest": {
201
- "version": "~28.1.1",
202
- "alwaysAddToPackageJson": false
203
- },
204
- "@types/jest": {
205
- "version": "~28.1.1",
206
- "alwaysAddToPackageJson": false
207
- },
208
- "expect": {
209
- "version": "~28.1.1",
210
- "alwaysAddToPackageJson": false
211
- },
212
- "@jest/globals": {
213
- "version": "~28.1.1",
214
- "alwaysAddToPackageJson": false
215
- },
216
- "jest-jasmine2": {
217
- "version": "~28.1.1",
218
- "alwaysAddToPackageJson": false
219
- },
220
- "jest-environment-jsdom": {
221
- "version": "~28.1.1",
222
- "alwaysAddToPackageJson": false
223
- },
224
- "ts-jest": {
225
- "version": "~28.0.5",
226
- "alwaysAddToPackageJson": false
227
- },
228
- "babel-jest": {
229
- "version": "~28.1.1",
230
- "alwaysAddToPackageJson": false
231
- }
232
- }
233
- },
234
35
  "15.0.1-beta.3": {
235
36
  "version": "15.0.1-beta.3",
236
37
  "packages": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/jest",
3
- "version": "16.10.0",
3
+ "version": "17.0.0-beta.1",
4
4
  "private": false,
5
5
  "description": "The Nx Plugin for Jest contains executors and generators allowing your workspace to use the powerful Jest testing capabilities.",
6
6
  "repository": {
@@ -44,9 +44,9 @@
44
44
  "jest-util": "^29.4.1",
45
45
  "resolve.exports": "1.1.0",
46
46
  "tslib": "^2.3.0",
47
- "@nx/devkit": "16.10.0",
48
- "@nx/js": "16.10.0",
49
- "@nrwl/jest": "16.10.0"
47
+ "@nx/devkit": "17.0.0-beta.1",
48
+ "@nx/js": "17.0.0-beta.1",
49
+ "@nrwl/jest": "17.0.0-beta.1"
50
50
  },
51
51
  "publishConfig": {
52
52
  "access": "public"
@@ -25,17 +25,6 @@ function updateWorkspace(tree, options) {
25
25
  },
26
26
  },
27
27
  };
28
- /**
29
- * @deprecated this will be removed in the v17
30
- */
31
- const isUsingTSLint = projectConfig.targets.lint?.executor ===
32
- '@angular-devkit/build-angular:tslint';
33
- if (isUsingTSLint) {
34
- projectConfig.targets.lint.options.tsConfig = [
35
- ...(projectConfig.targets.lint.options.tsConfig || []),
36
- (0, devkit_1.joinPathFragments)((0, devkit_1.normalizePath)(projectConfig.root), 'tsconfig.spec.json'),
37
- ];
38
- }
39
28
  (0, devkit_1.updateProjectConfiguration)(tree, options.project, projectConfig);
40
29
  }
41
30
  exports.updateWorkspace = updateWorkspace;
@@ -1 +0,0 @@
1
- export default function update(tree: any): Promise<void>;
@@ -1,51 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const devkit_1 = require("@nx/devkit");
4
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
5
- const path_1 = require("path");
6
- const update_config_1 = require("../../utils/config/update-config");
7
- function updateJestConfig(tree) {
8
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (options, projectName) => {
9
- const config = require((0, path_1.join)(tree.root, options.jestConfig));
10
- // migrate serializers
11
- if (config.snapshotSerializers &&
12
- Array.isArray(config.snapshotSerializers)) {
13
- const snapshotSerializers = config.snapshotSerializers.map((snapshotSerializer) => {
14
- switch (snapshotSerializer) {
15
- case 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js':
16
- return 'jest-preset-angular/build/serializers/no-ng-attributes';
17
- case 'jest-preset-angular/build/AngularSnapshotSerializer.js':
18
- return 'jest-preset-angular/build/serializers/ng-snapshot';
19
- case 'jest-preset-angular/build/HTMLCommentSerializer.js':
20
- return 'jest-preset-angular/build/serializers/html-comment';
21
- default:
22
- return snapshotSerializer;
23
- }
24
- });
25
- try {
26
- (0, update_config_1.removePropertyFromJestConfig)(tree, options.jestConfig, 'snapshotSerializers');
27
- (0, update_config_1.addPropertyToJestConfig)(tree, options.jestConfig, 'snapshotSerializers', snapshotSerializers);
28
- }
29
- catch {
30
- devkit_1.logger.error((0, devkit_1.stripIndents) `Unable to update snapshotSerializers for project ${projectName}.
31
- More information you can check online documentation https://github.com/thymikee/jest-preset-angular/blob/master/CHANGELOG.md#840-2021-03-04`);
32
- }
33
- }
34
- try {
35
- const { sourceRoot } = (0, devkit_1.readProjectConfiguration)(tree, projectName);
36
- const setupTestPath = (0, path_1.join)(sourceRoot, 'test-setup.ts');
37
- if (tree.exists(setupTestPath)) {
38
- const contents = tree.read(setupTestPath, 'utf-8');
39
- tree.write(setupTestPath, contents.replace(`import 'jest-preset-angular';`, `import 'jest-preset-angular/setup-jest';`));
40
- }
41
- }
42
- catch {
43
- devkit_1.logger.error((0, devkit_1.stripIndents) `Unable to update test-setup.ts for project ${projectName}.`);
44
- }
45
- });
46
- }
47
- async function update(tree) {
48
- updateJestConfig(tree);
49
- await (0, devkit_1.formatFiles)(tree);
50
- }
51
- exports.default = update;
@@ -1,2 +0,0 @@
1
- import { Tree } from '@nx/devkit';
2
- export default function update(tree: Tree): Promise<void>;
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const devkit_1 = require("@nx/devkit");
4
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
5
- const path_1 = require("path");
6
- const update_config_1 = require("../../utils/config/update-config");
7
- function updateJestConfig(tree) {
8
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (options, project) => {
9
- if (!options.jestConfig) {
10
- return;
11
- }
12
- const jestConfigPath = options.jestConfig;
13
- const config = require((0, path_1.join)(tree.root, jestConfigPath));
14
- const tsJestConfig = config.globals?.['ts-jest'];
15
- if (!(tsJestConfig && tsJestConfig.tsConfig)) {
16
- return;
17
- }
18
- try {
19
- (0, update_config_1.removePropertyFromJestConfig)(tree, jestConfigPath, 'globals.ts-jest.tsConfig');
20
- (0, update_config_1.addPropertyToJestConfig)(tree, jestConfigPath, 'globals.ts-jest.tsconfig', tsJestConfig.tsConfig);
21
- }
22
- catch {
23
- devkit_1.logger.error((0, devkit_1.stripIndents) `Unable to update jest.config.js for project ${project}.`);
24
- }
25
- });
26
- }
27
- async function update(tree) {
28
- updateJestConfig(tree);
29
- await (0, devkit_1.formatFiles)(tree);
30
- }
31
- exports.default = update;
@@ -1,2 +0,0 @@
1
- import { Tree } from '@nx/devkit';
2
- export default function update(tree: Tree): Promise<void>;
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const devkit_1 = require("@nx/devkit");
4
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
5
- const path_1 = require("path");
6
- const update_config_1 = require("../../utils/config/update-config");
7
- function updateJestConfig(tree) {
8
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (options, project) => {
9
- if (!options.jestConfig) {
10
- return;
11
- }
12
- const jestConfigPath = options.jestConfig;
13
- const jestConfig = require((0, path_1.join)(tree.root, jestConfigPath));
14
- const projectConfig = (0, devkit_1.readProjectConfiguration)(tree, project);
15
- const testEnvironment = jestConfig.testEnvironment;
16
- if (testEnvironment || !checkIfNodeProject(projectConfig)) {
17
- return;
18
- }
19
- try {
20
- (0, update_config_1.addPropertyToJestConfig)(tree, jestConfigPath, 'testEnvironment', 'node');
21
- }
22
- catch {
23
- devkit_1.logger.error((0, devkit_1.stripIndents) `Unable to update jest.config.js for project ${project}.`);
24
- }
25
- });
26
- }
27
- async function update(tree) {
28
- updateJestConfig(tree);
29
- await (0, devkit_1.formatFiles)(tree);
30
- }
31
- exports.default = update;
32
- function checkIfNodeProject(config) {
33
- return Object.entries(config.targets).some(([targetName, targetConfig]) => targetConfig.executor?.includes?.('node'));
34
- }
@@ -1,25 +0,0 @@
1
- import { Tree } from '@nx/devkit';
2
- export default function update(tree: Tree): Promise<void>;
3
- export declare function updateASTTransformers(tree: Tree, jestConfigPath: string, jestConfig: PartialJestConfig): void;
4
- export declare function updateTransform(tree: Tree, jestConfigPath: string, jestConfig: PartialJestConfig): void;
5
- interface PartialJestConfig {
6
- globals: {
7
- 'ts-jest': {
8
- astTransformers: ASTTransformers;
9
- };
10
- };
11
- transform?: Record<string, string>;
12
- }
13
- interface ASTTransformer {
14
- path: string;
15
- options: unknown;
16
- }
17
- interface ASTTransformers {
18
- before: (ASTTransformer | string)[];
19
- after: (ASTTransformer | string)[];
20
- afterDeclarations: (ASTTransformer | string)[];
21
- }
22
- export declare function getNewAstTransformers(astTransformers: ASTTransformers): ASTTransformers | null;
23
- export declare function transformerIsFromJestPresetAngular(transformer: ASTTransformer | string): boolean;
24
- export declare function usesJestPresetAngular(jestConfig: PartialJestConfig): boolean;
25
- export {};
@@ -1,82 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.usesJestPresetAngular = exports.transformerIsFromJestPresetAngular = exports.getNewAstTransformers = exports.updateTransform = exports.updateASTTransformers = void 0;
4
- const devkit_1 = require("@nx/devkit");
5
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
6
- const path_1 = require("path");
7
- const update_config_1 = require("../../utils/config/update-config");
8
- function updateJestConfig(tree) {
9
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (options, project) => {
10
- if (!options.jestConfig) {
11
- return;
12
- }
13
- const jestConfigPath = options.jestConfig;
14
- const jestConfig = require((0, path_1.join)(tree.root, jestConfigPath));
15
- if (!usesJestPresetAngular(jestConfig)) {
16
- return;
17
- }
18
- try {
19
- updateASTTransformers(tree, jestConfigPath, jestConfig);
20
- updateTransform(tree, jestConfigPath, jestConfig);
21
- }
22
- catch {
23
- devkit_1.logger.error((0, devkit_1.stripIndents) `Unable to update jest.config.js for project ${project}.`);
24
- }
25
- });
26
- }
27
- async function update(tree) {
28
- updateJestConfig(tree);
29
- await (0, devkit_1.formatFiles)(tree);
30
- }
31
- exports.default = update;
32
- function updateASTTransformers(tree, jestConfigPath, jestConfig) {
33
- const newTransformers = getNewAstTransformers(jestConfig.globals?.['ts-jest']?.astTransformers);
34
- if (newTransformers === null) {
35
- (0, update_config_1.removePropertyFromJestConfig)(tree, jestConfigPath, 'globals.ts-jest.astTransformers');
36
- }
37
- else {
38
- (0, update_config_1.addPropertyToJestConfig)(tree, jestConfigPath, 'globals.ts-jest.astTransformers', newTransformers);
39
- }
40
- }
41
- exports.updateASTTransformers = updateASTTransformers;
42
- function updateTransform(tree, jestConfigPath, jestConfig) {
43
- (0, update_config_1.removePropertyFromJestConfig)(tree, jestConfigPath, 'transform');
44
- (0, update_config_1.addPropertyToJestConfig)(tree, jestConfigPath, 'transform', {
45
- '^.+\\.(ts|js|html)$': 'jest-preset-angular',
46
- });
47
- }
48
- exports.updateTransform = updateTransform;
49
- function getNewAstTransformers(astTransformers) {
50
- let result = {
51
- before: astTransformers?.before?.filter?.((x) => !transformerIsFromJestPresetAngular(x)),
52
- after: astTransformers?.after?.filter?.((x) => !transformerIsFromJestPresetAngular(x)),
53
- afterDeclarations: astTransformers?.afterDeclarations?.filter?.((x) => !transformerIsFromJestPresetAngular(x)),
54
- };
55
- result = {
56
- before: result.before?.length > 0 ? result.before : undefined,
57
- after: result.after?.length > 0 ? result.after : undefined,
58
- afterDeclarations: result.afterDeclarations?.length > 0
59
- ? result.afterDeclarations
60
- : undefined,
61
- };
62
- if (!result.before && !result.after && !result.afterDeclarations) {
63
- return null;
64
- }
65
- else {
66
- return result;
67
- }
68
- }
69
- exports.getNewAstTransformers = getNewAstTransformers;
70
- function transformerIsFromJestPresetAngular(transformer) {
71
- return typeof transformer === 'string'
72
- ? transformer.includes('jest-preset-angular')
73
- : transformer.path.includes('jest-preset-angular');
74
- }
75
- exports.transformerIsFromJestPresetAngular = transformerIsFromJestPresetAngular;
76
- function usesJestPresetAngular(jestConfig) {
77
- const transformers = Array.isArray(jestConfig.globals?.['ts-jest']?.astTransformers)
78
- ? jestConfig.globals?.['ts-jest']?.astTransformers || []
79
- : jestConfig.globals?.['ts-jest']?.astTransformers?.before || [];
80
- return transformers.some((x) => transformerIsFromJestPresetAngular(x));
81
- }
82
- exports.usesJestPresetAngular = usesJestPresetAngular;
@@ -1,2 +0,0 @@
1
- import { Tree } from '@nx/devkit';
2
- export default function update(tree: Tree): Promise<void>;
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const devkit_1 = require("@nx/devkit");
4
- const functions_1 = require("../../utils/config/functions");
5
- const get_jest_projects_1 = require("../../utils/config/get-jest-projects");
6
- const update_config_1 = require("../../utils/config/update-config");
7
- function determineUncoveredJestProjects(existingProjects) {
8
- const coveredJestProjects = (0, get_jest_projects_1.getJestProjects)().reduce((acc, key) => {
9
- acc[key] = true;
10
- return acc;
11
- }, {});
12
- return existingProjects.filter((project) => !coveredJestProjects[project]);
13
- }
14
- function determineProjectsValue(uncoveredJestProjects) {
15
- if (!uncoveredJestProjects.length) {
16
- return `getJestProjects()`;
17
- }
18
- return `[...getJestProjects(), ${uncoveredJestProjects
19
- .map((projectName) => `'${projectName}', `)
20
- .join('')}]`;
21
- }
22
- function updateBaseJestConfig(tree, baseJestConfigPath = 'jest.config.js') {
23
- if (tree.read('/jest.config.js', 'utf-8').includes('getJestProjects()')) {
24
- return;
25
- }
26
- const currentConfig = (0, functions_1.jestConfigObject)(tree, baseJestConfigPath);
27
- currentConfig.projects ??= [];
28
- const uncoveredJestProjects = determineUncoveredJestProjects(currentConfig.projects);
29
- (0, update_config_1.removePropertyFromJestConfig)(tree, baseJestConfigPath, 'projects');
30
- (0, update_config_1.addPropertyToJestConfig)(tree, baseJestConfigPath, 'projects', determineProjectsValue(uncoveredJestProjects), { valueAsString: true });
31
- (0, update_config_1.addImportStatementToJestConfig)(tree, baseJestConfigPath, `const { getJestProjects } = require('@nx/jest');`);
32
- return;
33
- }
34
- async function update(tree) {
35
- updateBaseJestConfig(tree);
36
- await (0, devkit_1.formatFiles)(tree);
37
- }
38
- exports.default = update;
@@ -1,2 +0,0 @@
1
- import { Tree } from '@nx/devkit';
2
- export default function update(tree: Tree): Promise<void>;
@@ -1,56 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const devkit_1 = require("@nx/devkit");
4
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
5
- const path_1 = require("path");
6
- function updateTsConfigsForTests(tree) {
7
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (jestOptions, projectName) => {
8
- const projectConfig = (0, devkit_1.readProjectConfiguration)(tree, projectName);
9
- (0, devkit_1.visitNotIgnoredFiles)(tree, projectConfig.root, (path) => {
10
- const fileName = (0, path_1.basename)(path);
11
- if (fileName.startsWith('tsconfig') && fileName.endsWith('.json')) {
12
- updateTsConfig(tree, path);
13
- }
14
- });
15
- });
16
- function updateTsConfig(tree, tsconfigSpecPath) {
17
- try {
18
- (0, devkit_1.updateJson)(tree, tsconfigSpecPath, (value) => {
19
- if (value.include) {
20
- value.include = makeAllPatternsFromSpecPatterns(value.include);
21
- }
22
- if (value.exclude) {
23
- value.exclude = makeAllPatternsFromSpecPatterns(value.exclude);
24
- }
25
- return value;
26
- });
27
- }
28
- catch (error) {
29
- // issue trying to parse the tsconfig file bc it's invalid JSON from template markup/comments
30
- // ignore and move on
31
- devkit_1.logger.warn((0, devkit_1.stripIndents) `Unable to update ${tsconfigSpecPath}. `);
32
- }
33
- }
34
- }
35
- /**
36
- * take an array of patterns and create patterns from those containing .spec. with .test.
37
- * by default the pattern ** /*.spec.ts will be used if no value is passed in.
38
- */
39
- function makeAllPatternsFromSpecPatterns(specGlobs = ['**/*.spec.ts']) {
40
- return makeUniquePatterns(specGlobs.reduce((patterns, current) => {
41
- patterns.push(current);
42
- // .spec. and _spec. can used as testing file name patterns
43
- if (current.includes('spec.')) {
44
- patterns.push(current.replace('spec.', 'test.'));
45
- }
46
- return patterns;
47
- }, []));
48
- }
49
- function makeUniquePatterns(items = []) {
50
- return [...new Set(items)];
51
- }
52
- async function update(tree) {
53
- updateTsConfigsForTests(tree);
54
- await (0, devkit_1.formatFiles)(tree);
55
- }
56
- exports.default = update;
@@ -1,2 +0,0 @@
1
- import { Tree } from '@nx/devkit';
2
- export default function update(tree: Tree): Promise<void>;
@@ -1,39 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const devkit_1 = require("@nx/devkit");
4
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
5
- const functions_1 = require("../../utils/config/functions");
6
- const versions_1 = require("../../utils/versions");
7
- function checkIfProjectNeedsUpdate(tree) {
8
- if (tree.exists('babel.config.json')) {
9
- // the project is already running on babel and good to go
10
- return false;
11
- }
12
- let shouldUpdate = false;
13
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (jestOptions, projectName) => {
14
- const projectConfig = (0, devkit_1.readProjectConfiguration)(tree, projectName);
15
- const jestConfigPath = (0, devkit_1.joinPathFragments)(projectConfig.root, 'jest.config.js');
16
- if (!tree.exists(jestConfigPath)) {
17
- return;
18
- }
19
- const config = (0, functions_1.jestConfigObject)(tree, jestConfigPath);
20
- if (config.transform) {
21
- for (const transformer of Object.values(config.transform)) {
22
- if ((typeof transformer === 'string' && transformer === 'babel-jest') ||
23
- (Array.isArray(transformer) && transformer[0] === 'babel-jest')) {
24
- shouldUpdate = true;
25
- }
26
- }
27
- }
28
- });
29
- return shouldUpdate;
30
- }
31
- async function update(tree) {
32
- const shouldUpdateConfigs = checkIfProjectNeedsUpdate(tree);
33
- if (shouldUpdateConfigs) {
34
- (0, devkit_1.addDependenciesToPackageJson)(tree, {}, { '@nrwl/web': versions_1.nxVersion });
35
- tree.write('babel.config.json', '{"babelrcRoots": ["*"]}');
36
- await (0, devkit_1.formatFiles)(tree);
37
- }
38
- }
39
- exports.default = update;
@@ -1,3 +0,0 @@
1
- import { Tree } from '@nx/devkit';
2
- export declare function updateJestConfigExt(tree: Tree): Promise<void>;
3
- export default updateJestConfigExt;
@@ -1,110 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.updateJestConfigExt = void 0;
4
- const devkit_1 = require("@nx/devkit");
5
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
6
- const path_1 = require("path");
7
- const allowedExt = ['.ts', '.js'];
8
- function updateTsConfig(tree, tsConfigPath) {
9
- try {
10
- (0, devkit_1.updateJson)(tree, tsConfigPath, (json) => {
11
- json.exclude = Array.from(new Set([...(json.exclude || []), 'jest.config.ts']));
12
- return json;
13
- }, {
14
- allowTrailingComma: true,
15
- disallowComments: false,
16
- });
17
- }
18
- catch (e) {
19
- devkit_1.logger.warn((0, devkit_1.stripIndents) `Nx Unable to update ${tsConfigPath}. Please manually ignore the jest.config.ts file.`);
20
- }
21
- }
22
- function addEsLintIgnoreComments(tree, filePath) {
23
- if (tree.exists(filePath)) {
24
- const contents = tree.read(filePath, 'utf-8');
25
- if (!contents.startsWith('/* eslint-disable */')) {
26
- tree.write(filePath, `/* eslint-disable */
27
- ${contents}`);
28
- }
29
- }
30
- }
31
- function isJestConfigValid(tree, options) {
32
- const configExt = (0, path_1.extname)(options.jestConfig);
33
- if (!tree.exists(options.jestConfig) || !allowedExt.includes(configExt)) {
34
- devkit_1.logger.debug(`unable to update file because it doesn't exist or is not a js or ts file. Config: ${options.jestConfig}. Exists?: ${tree.exists(options.jestConfig)}`);
35
- return false;
36
- }
37
- return true;
38
- }
39
- function updateTsconfigSpec(tree, projectConfig, path, options = {
40
- isNextWithProjectParse: false,
41
- tsConfigPath: '',
42
- }) {
43
- (0, devkit_1.updateJson)(tree, (0, devkit_1.joinPathFragments)(projectConfig.root, path), (json) => {
44
- json.include = Array.from(new Set([...(json.include || []), 'jest.config.ts']));
45
- if (options.isNextWithProjectParse) {
46
- const tsConfig = (0, devkit_1.readJson)(tree, options.tsConfigPath);
47
- const tsConfigExclude = (tsConfig.exclude || []).filter((e) => e !== 'jest.config.ts');
48
- json.exclude = Array.from(new Set([...(json.exclude || []), ...tsConfigExclude]));
49
- }
50
- return json;
51
- });
52
- }
53
- function isNextWithProjectLint(projectConfig, esLintJson) {
54
- const esLintOverrides = esLintJson?.overrides?.find((o) => ['*.ts', '*.tsx', '*.js', '*.jsx'].every((ext) => o.files.includes(ext)));
55
- // check if it's a next app and has a parserOptions.project set in the eslint overrides
56
- return !!(projectConfig?.targets?.['build']?.executor === '@nrwl/next:build' &&
57
- esLintOverrides?.parserOptions?.project);
58
- }
59
- async function updateJestConfigExt(tree) {
60
- if (tree.exists('jest.config.js')) {
61
- tree.rename('jest.config.js', 'jest.config.ts');
62
- }
63
- const projects = (0, devkit_1.getProjects)(tree);
64
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (options, projectName, target, configuration) => {
65
- const projectConfig = projects.get(projectName);
66
- if (!options.jestConfig || !isJestConfigValid(tree, options)) {
67
- return;
68
- }
69
- addEsLintIgnoreComments(tree, options.jestConfig);
70
- const newJestConfigPath = options.jestConfig.replace('.js', '.ts');
71
- tree.rename(options.jestConfig, newJestConfigPath);
72
- const rootFiles = tree.children(projectConfig.root);
73
- for (const fileName of rootFiles) {
74
- if (fileName === 'tsconfig.json') {
75
- const filePath = (0, devkit_1.joinPathFragments)(projectConfig.root, fileName);
76
- const tsConfig = (0, devkit_1.readJson)(tree, filePath, {
77
- allowTrailingComma: true,
78
- disallowComments: false,
79
- });
80
- if (tsConfig.references) {
81
- for (const { path } of tsConfig.references) {
82
- // skip as editor.json should include everything anyway.
83
- if (path.endsWith('tsconfig.editor.json')) {
84
- continue;
85
- }
86
- if (path.endsWith('tsconfig.spec.json')) {
87
- const eslintPath = (0, devkit_1.joinPathFragments)(projectConfig.root, '.eslintrc.json');
88
- updateTsconfigSpec(tree, projectConfig, path, {
89
- isNextWithProjectParse: tree.exists(eslintPath)
90
- ? isNextWithProjectLint(projectConfig, (0, devkit_1.readJson)(tree, eslintPath))
91
- : false,
92
- tsConfigPath: filePath,
93
- });
94
- continue;
95
- }
96
- updateTsConfig(tree, (0, devkit_1.joinPathFragments)(projectConfig.root, path));
97
- }
98
- }
99
- else {
100
- updateTsConfig(tree, filePath);
101
- }
102
- }
103
- }
104
- projectConfig.targets[target].options.jestConfig = newJestConfigPath;
105
- (0, devkit_1.updateProjectConfiguration)(tree, projectName, projectConfig);
106
- });
107
- await (0, devkit_1.formatFiles)(tree);
108
- }
109
- exports.updateJestConfigExt = updateJestConfigExt;
110
- exports.default = updateJestConfigExt;
@@ -1,7 +0,0 @@
1
- import type { Tree } from '@nx/devkit';
2
- export declare function updateExportsJestConfig(tree: Tree): import("@nx/devkit").GeneratorCallback;
3
- export declare function updateRootFiles(tree: Tree): {
4
- didUpdateRootPreset: boolean;
5
- };
6
- export declare function updateToDefaultExport(tree: Tree, filePath: string): void;
7
- export default updateExportsJestConfig;
@@ -1,65 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.updateToDefaultExport = exports.updateRootFiles = exports.updateExportsJestConfig = void 0;
4
- const devkit_1 = require("@nx/devkit");
5
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
6
- const versions_1 = require("../../utils/versions");
7
- const tsquery_1 = require("@phenomnomnominal/tsquery");
8
- function updateExportsJestConfig(tree) {
9
- const { didUpdateRootPreset } = updateRootFiles(tree);
10
- let shouldInstallTsNode = false;
11
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (options) => {
12
- if (options.jestConfig && tree.exists(options.jestConfig)) {
13
- if (options.jestConfig.endsWith('.ts')) {
14
- updateToDefaultExport(tree, options.jestConfig);
15
- shouldInstallTsNode = true;
16
- }
17
- const updatedImport = updateNxPresetImport(tree.read(options.jestConfig, 'utf-8'));
18
- tree.write(options.jestConfig, updatedImport);
19
- // jest.preset.ts => jest.preset.js
20
- if (didUpdateRootPreset) {
21
- const projectConfig = tree.read(options.jestConfig, 'utf-8');
22
- const updatedConfig = projectConfig.replace(/(preset:\s*['"][.\/]*)(jest\.preset\.ts)(['"])/g, '$1jest.preset.js$3');
23
- tree.write(options.jestConfig, updatedConfig);
24
- }
25
- }
26
- });
27
- return shouldInstallTsNode
28
- ? (0, devkit_1.addDependenciesToPackageJson)(tree, {}, { 'ts-node': versions_1.tsNodeVersion })
29
- : () => { };
30
- }
31
- exports.updateExportsJestConfig = updateExportsJestConfig;
32
- function updateRootFiles(tree) {
33
- let didUpdateRootPreset = false;
34
- if (tree.exists('jest.config.ts')) {
35
- updateToDefaultExport(tree, 'jest.config.ts');
36
- }
37
- if (tree.exists('jest.preset.ts')) {
38
- // fix those who ran v14 migration where this was renamed.
39
- tree.rename('jest.preset.ts', 'jest.preset.js');
40
- didUpdateRootPreset = true;
41
- }
42
- if (tree.exists('jest.preset.js')) {
43
- const newContents = updateNxPresetImport(tree.read('jest.preset.js', 'utf-8'));
44
- tree.write('jest.preset.js', newContents);
45
- }
46
- return {
47
- didUpdateRootPreset,
48
- };
49
- }
50
- exports.updateRootFiles = updateRootFiles;
51
- function updateNxPresetImport(fileContents) {
52
- return fileContents.replace(/require\(['"]@nrwl\/jest\/preset['"]\)[;\s]*?[\n\r]/g, `require('@nrwl/jest/preset').default;
53
- `);
54
- }
55
- function updateToDefaultExport(tree, filePath) {
56
- const newConfig = tsquery_1.tsquery.replace(tree.read(filePath, 'utf-8'), 'ExpressionStatement BinaryExpression', (node) => {
57
- if (node.left.getText() === 'module.exports') {
58
- return `export default ${node.right.getText()}`;
59
- }
60
- return node.getText();
61
- });
62
- tree.write(filePath, newConfig);
63
- }
64
- exports.updateToDefaultExport = updateToDefaultExport;
65
- exports.default = updateExportsJestConfig;
@@ -1,5 +0,0 @@
1
- import { Tree } from '@nx/devkit';
2
- export declare function updateConfigsJest28(tree: Tree): import("@nx/devkit").GeneratorCallback;
3
- export declare function updateJestConfig(config: string): string;
4
- export declare function checkDeps(tree: Tree): Record<string, string>;
5
- export default updateConfigsJest28;
@@ -1,80 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.checkDeps = exports.updateJestConfig = exports.updateConfigsJest28 = void 0;
4
- const devkit_1 = require("@nx/devkit");
5
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
6
- const tsquery_1 = require("@phenomnomnominal/tsquery");
7
- const typescript_1 = require("typescript");
8
- const find_root_jest_files_1 = require("../../utils/config/find-root-jest-files");
9
- const jestVersion = '28.1.1';
10
- const JASMINE_TEST_RUNNER = /(testRunner:\s*['"`])(jest-jasmine2)(['"`])/g;
11
- const JSDOM_TEST_ENV = /(testEnvironment:\s*['"`])(jsdom)(['"`])/g;
12
- function updateConfigsJest28(tree) {
13
- let devDeps = checkDeps(tree);
14
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (options) => {
15
- if (options.jestConfig && tree.exists(options.jestConfig)) {
16
- const updatedConfig = updateJestConfig(tree.read(options.jestConfig, 'utf-8'));
17
- tree.write(options.jestConfig, updatedConfig);
18
- const projectConfigCheck = testFileForDep(updatedConfig);
19
- devDeps = { ...devDeps, ...projectConfigCheck };
20
- }
21
- });
22
- return (0, devkit_1.addDependenciesToPackageJson)(tree, {}, devDeps);
23
- }
24
- exports.updateConfigsJest28 = updateConfigsJest28;
25
- function updateJestConfig(config) {
26
- let content = tsquery_1.tsquery.replace(config, 'PropertyAssignment:has(Identifier[name="testURL"])', (node) => {
27
- const value = node?.initializer?.getText();
28
- return `testEnvironmentOptions: {url: ${value}}`;
29
- });
30
- content = tsquery_1.tsquery.replace(content, 'PropertyAssignment > Identifier[name="extraGlobals"]', () => {
31
- return 'sandboxInjectedGlobals';
32
- });
33
- return tsquery_1.tsquery.replace(content, 'PropertyAssignment:has(Identifier[name="timers"])', (node) => {
34
- // must guard against non string properties as that means it's already been manually migrated
35
- if (node?.initializer && (0, typescript_1.isStringLiteralLike)(node.initializer)) {
36
- const value = node?.initializer.getText().trim();
37
- // use .includes to ignore the different quotes (' " `)
38
- if (value.includes('fake') || value.includes('modern')) {
39
- return `fakeTimers: { enableGlobally: true }`;
40
- }
41
- if (value.includes('real')) {
42
- return `fakeTimers: { enableGlobally: false }`;
43
- }
44
- if (value.includes('legacy')) {
45
- return `fakeTimers: { enableGlobally: true, legacyFakeTimers: true }`;
46
- }
47
- }
48
- });
49
- }
50
- exports.updateJestConfig = updateJestConfig;
51
- function checkDeps(tree) {
52
- const packageJson = (0, devkit_1.readJson)(tree, 'package.json');
53
- let devDeps = {};
54
- if (packageJson.devDependencies['jest-preset-angular']) {
55
- devDeps['jest-environment-jsdom'] = jestVersion;
56
- }
57
- const rootJestConfig = (0, find_root_jest_files_1.findRootJestConfig)(tree);
58
- if (rootJestConfig) {
59
- const rootConfigCheck = testFileForDep(tree.read(rootJestConfig, 'utf-8'));
60
- devDeps = { ...devDeps, ...rootConfigCheck };
61
- }
62
- const rootJestPreset = (0, find_root_jest_files_1.findRootJestPreset)(tree);
63
- if (rootJestPreset) {
64
- const rootPresetCheck = testFileForDep(tree.read(rootJestPreset, 'utf-8'));
65
- devDeps = { ...devDeps, ...rootPresetCheck };
66
- }
67
- return devDeps;
68
- }
69
- exports.checkDeps = checkDeps;
70
- function testFileForDep(config) {
71
- const deps = {};
72
- if (JASMINE_TEST_RUNNER.test(config)) {
73
- deps['jest-jasmine2'] = jestVersion;
74
- }
75
- if (JSDOM_TEST_ENV.test(config)) {
76
- deps['jest-environment-jsdom'] = jestVersion;
77
- }
78
- return deps;
79
- }
80
- exports.default = updateConfigsJest28;
@@ -1,24 +0,0 @@
1
- import { Tree } from '@nx/devkit';
2
- export declare function updateTestsJest28(tree: Tree): void;
3
- /**
4
- * jest.useFakeTimers('modern') -> jest.useFakeTimers()
5
- * jest.useFakeTimers('legacy') -> jest.useFakeTimers({legacyFakeTimers: true})
6
- * if legacyFakeTimers is true in config, then
7
- * jest.useFakeTimers('modern') -> jest.useRealTimers({legacyFakeTimers: false})
8
- */
9
- export declare function updateJestTimers(fileContents: string, legacyFakeTimersInConfig: boolean): string;
10
- /**
11
- * this only applies to tests using @jest/globals
12
- * jest.fn<Promise<string>, []>() -> jest.fn<() => Promise<string>>()
13
- * jest.fn<number, string[]>() -> jest.fn<() => number>()
14
- * jest.fn<ReturnType<typeof add>, Parameters<typeof add>>(); -> jest.fn<typeof add>()
15
- */
16
- export declare function updateJestFnMocks(fileContents: string): string;
17
- /**
18
- * import expect from 'expect' -> import { expect } from 'expect'
19
- * const expect = require('expect') -> const { expect } = require('expect')
20
- * import { mocked } from 'ts-jest/utils' => import { mocked } from 'jest-mock';
21
- * const { mocked } = require('ts-jest/utils'); => const { mocked } = require('jest-mock');
22
- */
23
- export declare function updateJestImports(content: string): string;
24
- export default updateTestsJest28;
@@ -1,153 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.updateJestImports = exports.updateJestFnMocks = exports.updateJestTimers = exports.updateTestsJest28 = void 0;
4
- const devkit_1 = require("@nx/devkit");
5
- const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
6
- const tsquery_1 = require("@phenomnomnominal/tsquery");
7
- const ts = require("typescript");
8
- function updateTestsJest28(tree) {
9
- const testFilePatterns = /.*.(spec|test)\.(ts|js)x?/g;
10
- const legacyTimers = /(timers:\s*['"`]legacy['"`])|(legacyFakeTimers:\s*true)/g;
11
- (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (options, projectName) => {
12
- const projectConfig = (0, devkit_1.readProjectConfiguration)(tree, projectName);
13
- const isUsingLegacyTimers = options.jestConfig &&
14
- tree.exists(options.jestConfig) &&
15
- legacyTimers.test(tree.read(options.jestConfig, 'utf-8'));
16
- (0, devkit_1.visitNotIgnoredFiles)(tree, projectConfig.root, (filePath) => {
17
- if (!filePath.match(testFilePatterns)) {
18
- return;
19
- }
20
- let fileContent = tree.read(filePath, 'utf-8');
21
- fileContent = updateJestTimers(fileContent, isUsingLegacyTimers);
22
- if (fileContent.includes('@jest/globals')) {
23
- fileContent = updateJestFnMocks(fileContent);
24
- }
25
- fileContent = updateJestImports(fileContent);
26
- tree.write(filePath, fileContent);
27
- });
28
- });
29
- }
30
- exports.updateTestsJest28 = updateTestsJest28;
31
- /**
32
- * jest.useFakeTimers('modern') -> jest.useFakeTimers()
33
- * jest.useFakeTimers('legacy') -> jest.useFakeTimers({legacyFakeTimers: true})
34
- * if legacyFakeTimers is true in config, then
35
- * jest.useFakeTimers('modern') -> jest.useRealTimers({legacyFakeTimers: false})
36
- */
37
- function updateJestTimers(fileContents, legacyFakeTimersInConfig) {
38
- return tsquery_1.tsquery.replace(fileContents, 'CallExpression', (node) => {
39
- if (!node?.getText().startsWith('jest.useFakeTimers')) {
40
- return;
41
- }
42
- const timerType = node.getText();
43
- // will be modern or legacy with quotes
44
- // just make sure it's included to ignore different quote types
45
- if (timerType.includes('legacy')) {
46
- return 'jest.useFakeTimers({ legacyFakeTimers: true })';
47
- }
48
- if (legacyFakeTimersInConfig) {
49
- // using modern but have config set to legacy
50
- return 'jest.useRealTimers({ legacyFakeTimers: false })';
51
- }
52
- // have to include space otherwise empty string will not remove the string literal
53
- return 'jest.useFakeTimers()';
54
- });
55
- }
56
- exports.updateJestTimers = updateJestTimers;
57
- /**
58
- * make sure using jest.fn<T>
59
- */
60
- function isTypedJestFnMock(node) {
61
- return ts.isCallExpression(node) && node.getText().startsWith('jest.fn<');
62
- }
63
- /**
64
- * has 2 args where the second is a tuple or array
65
- * i.e.
66
- * jest.fn<Promise<string>, []>()
67
- * jest.fn<number, MyType[]>()
68
- * jest.fn<number, [string, number, SomeType]>()
69
- */
70
- function isValid2Args(node) {
71
- const r = node?.typeArguments.length === 2 &&
72
- (node.typeArguments[1]?.kind === ts.SyntaxKind.TupleType ||
73
- node.typeArguments[1]?.kind === ts.SyntaxKind.ArrayType);
74
- return r;
75
- }
76
- /**
77
- * has 1 arg where the type is NOT a FunctionType
78
- * if it's a function type then it's already using the correct syntax
79
- * i.e.
80
- * jest.fn<string>()
81
- * jest.fn<() => Promise<string>>() is already valid, don't change it.
82
- */
83
- function isValid1Arg(node) {
84
- const r = node?.typeArguments.length === 1 &&
85
- node.typeArguments[0]?.kind !== ts.SyntaxKind.FunctionType &&
86
- node.typeArguments[0]?.kind !== ts.SyntaxKind.TypeQuery;
87
- return r;
88
- }
89
- /**
90
- * has a type reference as a type args
91
- * jest.fn<ReturnType<typeof add>, Parameters<typeof add>>();
92
- */
93
- function isValidTypeRef(node) {
94
- const r = node.typeArguments[0].kind === ts.SyntaxKind.TypeReference &&
95
- !!node.typeArguments?.[0]?.typeArguments;
96
- return r;
97
- }
98
- /**
99
- * has valid type args. prevent converting an already converted jest.fn<T>()
100
- */
101
- function isValidType(node) {
102
- const r = node?.typeArguments.length === 1 &&
103
- (node.typeArguments[0]?.kind === ts.SyntaxKind.FunctionType ||
104
- node.typeArguments[0]?.kind === ts.SyntaxKind.TypeReference ||
105
- node.typeArguments[0]?.kind === ts.SyntaxKind.TypeQuery ||
106
- node.parent.getText().includes('/** TODO:')); // has already been marked by a previous run.
107
- return r;
108
- }
109
- /**
110
- * this only applies to tests using @jest/globals
111
- * jest.fn<Promise<string>, []>() -> jest.fn<() => Promise<string>>()
112
- * jest.fn<number, string[]>() -> jest.fn<() => number>()
113
- * jest.fn<ReturnType<typeof add>, Parameters<typeof add>>(); -> jest.fn<typeof add>()
114
- */
115
- function updateJestFnMocks(fileContents) {
116
- return tsquery_1.tsquery.replace(fileContents, 'CallExpression', (node) => {
117
- if (!isTypedJestFnMock(node) || isValidType(node)) {
118
- return;
119
- }
120
- if (isValid2Args(node) || isValid1Arg(node)) {
121
- return `${node.getText().split('<')[0]}<() => ${node.typeArguments[0].getText()}>()`;
122
- }
123
- if (isValidTypeRef(node)) {
124
- const innerType = node.typeArguments[0]
125
- .typeArguments;
126
- return `${node.getText().split('<')[0]}<${innerType[0].getText()}>()`;
127
- }
128
- return `/** TODO: Update jest.fn<T>() type args for Jest v28 https://jestjs.io/docs/upgrading-to-jest28#jestfn */ ${node.getText()}`;
129
- });
130
- }
131
- exports.updateJestFnMocks = updateJestFnMocks;
132
- /**
133
- * import expect from 'expect' -> import { expect } from 'expect'
134
- * const expect = require('expect') -> const { expect } = require('expect')
135
- * import { mocked } from 'ts-jest/utils' => import { mocked } from 'jest-mock';
136
- * const { mocked } = require('ts-jest/utils'); => const { mocked } = require('jest-mock');
137
- */
138
- function updateJestImports(content) {
139
- const mockUpdatedImports = tsquery_1.tsquery.replace(content, ':matches(ImportDeclaration:has(Identifier[name="mocked"]) StringLiteral[value="ts-jest/utils"], VariableStatement:has(Identifier[name="mocked"]) StringLiteral[value="ts-jest/utils"])', () => {
140
- return "'jest-mock'";
141
- });
142
- return tsquery_1.tsquery.replace(mockUpdatedImports, ':matches(ImportDeclaration:has(StringLiteral[value="expect"]), VariableDeclaration:has(StringLiteral[value="expect"]))', (node) => {
143
- if (ts.isImportDeclaration(node)) {
144
- return `import { expect } from 'expect';`;
145
- }
146
- if (ts.isVariableDeclaration(node)) {
147
- return `{ expect } = require('expect')`; // this query doesn't capture the ; so we don't need to add it in the replace.
148
- }
149
- return;
150
- });
151
- }
152
- exports.updateJestImports = updateJestImports;
153
- exports.default = updateTestsJest28;