@nx/jest 0.0.0-pr-22179-271588f

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 (80) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +68 -0
  3. package/executors.json +10 -0
  4. package/generators.json +19 -0
  5. package/index.d.ts +8 -0
  6. package/index.js +19 -0
  7. package/migrations.json +105 -0
  8. package/package.json +57 -0
  9. package/plugin.d.ts +1 -0
  10. package/plugin.js +6 -0
  11. package/plugins/resolver.d.ts +1 -0
  12. package/plugins/resolver.js +58 -0
  13. package/preset/index.d.ts +2 -0
  14. package/preset/index.js +4 -0
  15. package/preset/jest-preset.d.ts +2 -0
  16. package/preset/jest-preset.js +33 -0
  17. package/src/executors/jest/jest.impl.d.ts +10 -0
  18. package/src/executors/jest/jest.impl.js +179 -0
  19. package/src/executors/jest/schema.d.ts +44 -0
  20. package/src/executors/jest/schema.json +226 -0
  21. package/src/executors/jest/summary.d.ts +7 -0
  22. package/src/executors/jest/summary.js +154 -0
  23. package/src/generators/configuration/configuration.d.ts +5 -0
  24. package/src/generators/configuration/configuration.js +90 -0
  25. package/src/generators/configuration/files/jest.config.ts__tmpl__ +16 -0
  26. package/src/generators/configuration/files/src/test-setup.ts__tmpl__ +0 -0
  27. package/src/generators/configuration/files/tsconfig.spec.json__tmpl__ +21 -0
  28. package/src/generators/configuration/files-angular/jest.config.ts__tmpl__ +27 -0
  29. package/src/generators/configuration/files-angular/src/test-setup.ts__tmpl__ +1 -0
  30. package/src/generators/configuration/files-angular/tsconfig.spec.json__tmpl__ +22 -0
  31. package/src/generators/configuration/lib/check-for-test-target.d.ts +3 -0
  32. package/src/generators/configuration/lib/check-for-test-target.js +11 -0
  33. package/src/generators/configuration/lib/create-files.d.ts +3 -0
  34. package/src/generators/configuration/lib/create-files.js +47 -0
  35. package/src/generators/configuration/lib/create-jest-config.d.ts +3 -0
  36. package/src/generators/configuration/lib/create-jest-config.js +102 -0
  37. package/src/generators/configuration/lib/ensure-dependencies.d.ts +3 -0
  38. package/src/generators/configuration/lib/ensure-dependencies.js +34 -0
  39. package/src/generators/configuration/lib/update-jestconfig.d.ts +3 -0
  40. package/src/generators/configuration/lib/update-jestconfig.js +26 -0
  41. package/src/generators/configuration/lib/update-tsconfig.d.ts +3 -0
  42. package/src/generators/configuration/lib/update-tsconfig.js +21 -0
  43. package/src/generators/configuration/lib/update-vscode-recommended-extensions.d.ts +2 -0
  44. package/src/generators/configuration/lib/update-vscode-recommended-extensions.js +18 -0
  45. package/src/generators/configuration/lib/update-workspace.d.ts +3 -0
  46. package/src/generators/configuration/lib/update-workspace.js +23 -0
  47. package/src/generators/configuration/schema.d.ts +31 -0
  48. package/src/generators/configuration/schema.json +80 -0
  49. package/src/generators/init/init.d.ts +5 -0
  50. package/src/generators/init/init.js +106 -0
  51. package/src/generators/init/schema.d.ts +8 -0
  52. package/src/generators/init/schema.json +35 -0
  53. package/src/migrations/update-15-0-0/add-jest-inputs.d.ts +2 -0
  54. package/src/migrations/update-15-0-0/add-jest-inputs.js +41 -0
  55. package/src/migrations/update-15-8-0/update-configs-jest-29.d.ts +3 -0
  56. package/src/migrations/update-15-8-0/update-configs-jest-29.js +146 -0
  57. package/src/migrations/update-15-8-0/update-tests-jest-29.d.ts +5 -0
  58. package/src/migrations/update-15-8-0/update-tests-jest-29.js +60 -0
  59. package/src/migrations/update-16-0-0-add-nx-packages/update-16-0-0-add-nx-packages.d.ts +2 -0
  60. package/src/migrations/update-16-0-0-add-nx-packages/update-16-0-0-add-nx-packages.js +9 -0
  61. package/src/migrations/update-16-5-0/add-test-setup-to-inputs-ignore.d.ts +3 -0
  62. package/src/migrations/update-16-5-0/add-test-setup-to-inputs-ignore.js +18 -0
  63. package/src/migrations/update-17-1-0/move-options-to-target-defaults.d.ts +2 -0
  64. package/src/migrations/update-17-1-0/move-options-to-target-defaults.js +117 -0
  65. package/src/plugins/plugin.d.ts +6 -0
  66. package/src/plugins/plugin.js +130 -0
  67. package/src/utils/ast-utils.d.ts +9 -0
  68. package/src/utils/ast-utils.js +32 -0
  69. package/src/utils/config/find-root-jest-files.d.ts +3 -0
  70. package/src/utils/config/find-root-jest-files.js +23 -0
  71. package/src/utils/config/functions.d.ts +17 -0
  72. package/src/utils/config/functions.js +211 -0
  73. package/src/utils/config/get-jest-projects.d.ts +34 -0
  74. package/src/utils/config/get-jest-projects.js +157 -0
  75. package/src/utils/config/is-preset-cjs.d.ts +2 -0
  76. package/src/utils/config/is-preset-cjs.js +15 -0
  77. package/src/utils/config/update-config.d.ts +20 -0
  78. package/src/utils/config/update-config.js +83 -0
  79. package/src/utils/versions.d.ts +9 -0
  80. package/src/utils/versions.js +12 -0
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateConfigsJest29 = 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 ast_utils_1 = require("../../utils/ast-utils");
7
+ const tsquery_1 = require("@phenomnomnominal/tsquery");
8
+ const ts = require("typescript");
9
+ const find_root_jest_files_1 = require("../../utils/config/find-root-jest-files");
10
+ async function updateConfigsJest29(tree) {
11
+ const rootPreset = (0, find_root_jest_files_1.findRootJestPreset)(tree);
12
+ const targetsWithJest = new Set();
13
+ // have to use graph so the negative configuration targets are expanded
14
+ const graph = await (0, devkit_1.createProjectGraphAsync)();
15
+ (0, executor_options_utils_1.forEachExecutorOptionsInGraph)(graph, '@nrwl/jest:jest', (options, projectName, targetName) => {
16
+ if (options.jestConfig && tree.exists(options.jestConfig)) {
17
+ targetsWithJest.add(targetName);
18
+ // if the default root preset exists or if the project doesn't have a 'preset' configured
19
+ // -> update snapshot config
20
+ if (!rootPreset || !hasPresetConfigured(tree, options.jestConfig)) {
21
+ addSnapshotOptionsToConfig(tree, options.jestConfig, `From within the project directory, run "nx test --update-snapshot"`);
22
+ }
23
+ updateTsJestOptions(tree, options.jestConfig);
24
+ updateNgJestOptions(tree, options.jestConfig);
25
+ }
26
+ });
27
+ if (rootPreset && tree.exists(rootPreset)) {
28
+ const cmd = `"nx affected --targets=${Array.from(targetsWithJest).join(',')} --update-snapshot"`;
29
+ addSnapshotOptionsToConfig(tree, rootPreset, cmd);
30
+ updateTsJestOptions(tree, rootPreset);
31
+ updateNgJestOptions(tree, rootPreset);
32
+ }
33
+ await (0, devkit_1.formatFiles)(tree);
34
+ devkit_1.logger.info((0, devkit_1.stripIndents) `NX Jest Snapshot format changed in v29.
35
+ By default Nx kept the older style to prevent breaking of existing tests with snapshots.
36
+ It's recommend you update to the latest format.
37
+ You can do this in your project's jest config file.
38
+ Remove the snapshotFormat property and re-run tests with the --update-snapshot flag.
39
+ More info: https://jestjs.io/docs/upgrading-to-jest29#snapshot-format`);
40
+ }
41
+ exports.updateConfigsJest29 = updateConfigsJest29;
42
+ function addSnapshotOptionsToConfig(tree, configPath, updateSnapshotExample) {
43
+ const config = tree.read(configPath, 'utf-8');
44
+ const hasSnapshotOptions = tsquery_1.tsquery.query(config, `${ast_utils_1.TS_QUERY_JEST_CONFIG_PREFIX} > ObjectLiteralExpression PropertyAssignment:has(Identifier[name="snapshotFormat"])`);
45
+ if (hasSnapshotOptions.length > 0) {
46
+ return;
47
+ }
48
+ const updatedConfig = tsquery_1.tsquery.replace(config, `${ast_utils_1.TS_QUERY_JEST_CONFIG_PREFIX} > ObjectLiteralExpression`, (node) => {
49
+ return `{
50
+ ${node.properties.map((p) => getNodeWithComments(config, p)).join(',\n')},
51
+ /* TODO: Update to latest Jest snapshotFormat
52
+ * By default Nx has kept the older style of Jest Snapshot formats
53
+ * to prevent breaking of any existing tests with snapshots.
54
+ * It's recommend you update to the latest format.
55
+ * You can do this by removing snapshotFormat property
56
+ * and running tests with --update-snapshot flag.
57
+ * Example: ${updateSnapshotExample}
58
+ * More info: https://jestjs.io/docs/upgrading-to-jest29#snapshot-format
59
+ */
60
+ snapshotFormat: { escapeString: true, printBasicPrototype: true }
61
+ }`;
62
+ }, { visitAllChildren: false });
63
+ tree.write(configPath, updatedConfig);
64
+ }
65
+ function hasPresetConfigured(tree, configPath) {
66
+ const contents = tree.read(configPath, 'utf-8');
67
+ return (tsquery_1.tsquery.query(contents, `${ast_utils_1.TS_QUERY_JEST_CONFIG_PREFIX} > ObjectLiteralExpression PropertyAssignment:has(Identifier[name="preset"])`)?.length > 0);
68
+ }
69
+ function updateTsJestOptions(tree, configPath) {
70
+ // query for the globals property, if they don't have one then there's nothing to modify.
71
+ const contents = tree.read(configPath, 'utf-8');
72
+ let tsJestGlobalsConfig;
73
+ const noTsJestGlobals = tsquery_1.tsquery.replace(contents, `${ast_utils_1.TS_QUERY_JEST_CONFIG_PREFIX} > ObjectLiteralExpression PropertyAssignment:has(Identifier[name="globals"])`, (node) => {
74
+ if (tsJestGlobalsConfig) {
75
+ devkit_1.logger.warn((0, devkit_1.stripIndents) `Found more than one "globals" object in the jest config, ${configPath}
76
+ Will use the first one`);
77
+ return;
78
+ }
79
+ tsJestGlobalsConfig = getGlobalTsJestConfig(node);
80
+ return getGlobalConfigWithoutTsJest(node);
81
+ });
82
+ if (!tsJestGlobalsConfig) {
83
+ return;
84
+ }
85
+ const updatedTsJestTransformer = tsquery_1.tsquery.replace(noTsJestGlobals, `${ast_utils_1.TS_QUERY_JEST_CONFIG_PREFIX}> ObjectLiteralExpression PropertyAssignment:has(Identifier[name="transform"]) PropertyAssignment > :has(StringLiteral[value="ts-jest"], StringLiteral[value="jest-preset-angular"])`, (node) => {
86
+ return `[${node.getText()}, ${tsJestGlobalsConfig}]`;
87
+ });
88
+ tree.write(configPath, updatedTsJestTransformer);
89
+ }
90
+ function updateNgJestOptions(tree, configPath) {
91
+ const contents = tree.read(configPath, 'utf-8');
92
+ let ngJestTeardownConfig;
93
+ const noTeardownConfig = tsquery_1.tsquery.replace(contents, 'BinaryExpression:has(PropertyAccessExpression:has(Identifier[name=ngJest])) PropertyAssignment:has(Identifier[name=teardown])', (node) => {
94
+ ngJestTeardownConfig = node.initializer.getText();
95
+ return ' ';
96
+ });
97
+ if (!ngJestTeardownConfig) {
98
+ return;
99
+ }
100
+ let maybeUpdatedTestEnvOpts = tsquery_1.tsquery.replace(noTeardownConfig, `${ast_utils_1.TS_QUERY_JEST_CONFIG_PREFIX} > ObjectLiteralExpression PropertyAssignment:has(Identifier[name="testEnvironmentOptions"]) ObjectLiteralExpression`, (node) => {
101
+ return `{
102
+ ${node.properties
103
+ .map((p) => getNodeWithComments(noTeardownConfig, p))
104
+ .join(',\n')},
105
+ teardown: ${ngJestTeardownConfig}
106
+ }`;
107
+ });
108
+ if (maybeUpdatedTestEnvOpts !== noTeardownConfig) {
109
+ tree.write(configPath, maybeUpdatedTestEnvOpts);
110
+ return;
111
+ }
112
+ // didn't find existing testEnvironmentOptions, so add the new property
113
+ const updatedConfig = tsquery_1.tsquery.replace(maybeUpdatedTestEnvOpts, `${ast_utils_1.TS_QUERY_JEST_CONFIG_PREFIX} > ObjectLiteralExpression`, (node) => {
114
+ return `{
115
+ ${node.properties
116
+ .map((p) => getNodeWithComments(maybeUpdatedTestEnvOpts, p))
117
+ .join(',\n')},
118
+ testEnvironmentOptions: { teardown: ${ngJestTeardownConfig} },
119
+ }`;
120
+ }, { visitAllChildren: false });
121
+ tree.write(configPath, updatedConfig);
122
+ }
123
+ function getGlobalTsJestConfig(node) {
124
+ const globalObject = node.initializer;
125
+ const foundConfig = globalObject.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText().includes('ts-jest'));
126
+ return foundConfig?.initializer?.getText() || '';
127
+ }
128
+ function getGlobalConfigWithoutTsJest(node) {
129
+ const globalObject = node?.initializer;
130
+ const withoutTsJest = globalObject?.properties?.filter((p) => {
131
+ return !(ts.isPropertyAssignment(p) && p.name.getText().includes('ts-jest'));
132
+ });
133
+ const globalConfigs = withoutTsJest.map((c) => c.getText()).join(',\n');
134
+ return `globals: { ${globalConfigs} }`;
135
+ }
136
+ function getNodeWithComments(fullText, node) {
137
+ const commentRanges = ts.getLeadingCommentRanges(fullText, node.getFullStart());
138
+ if (commentRanges?.length > 0) {
139
+ const withComments = `${commentRanges
140
+ .map((r) => fullText.slice(r.pos, r.end))
141
+ .join('\n')}\n${node.getText()}`;
142
+ return withComments;
143
+ }
144
+ return node.getText();
145
+ }
146
+ exports.default = updateConfigsJest29;
@@ -0,0 +1,5 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export declare function updateTestsJest29(tree: Tree): Promise<void>;
3
+ export declare function updateJestMockTypes(tree: Tree, filePath: string): void;
4
+ export declare function updateJestMocked(tree: Tree, filePath: string): void;
5
+ export default updateTestsJest29;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateJestMocked = exports.updateJestMockTypes = exports.updateTestsJest29 = 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 ast_utils_1 = require("../../utils/ast-utils");
8
+ async function updateTestsJest29(tree) {
9
+ const graph = await (0, devkit_1.createProjectGraphAsync)();
10
+ (0, executor_options_utils_1.forEachExecutorOptionsInGraph)(graph, '@nrwl/jest:jest', (options, projectName) => {
11
+ const projectConfig = (0, devkit_1.readProjectConfiguration)(tree, projectName);
12
+ (0, devkit_1.visitNotIgnoredFiles)(tree, projectConfig.sourceRoot || projectConfig.root, (file) => {
13
+ if (!ast_utils_1.TEST_FILE_PATTERN.test(file)) {
14
+ return;
15
+ }
16
+ updateJestMockTypes(tree, file);
17
+ updateJestMocked(tree, file);
18
+ });
19
+ });
20
+ await (0, devkit_1.formatFiles)(tree);
21
+ }
22
+ exports.updateTestsJest29 = updateTestsJest29;
23
+ function updateJestMockTypes(tree, filePath) {
24
+ const contents = tree.read(filePath, 'utf-8');
25
+ const updatedContent = tsquery_1.tsquery.replace(contents, ':matches(ImportDeclaration, VariableStatement):has(Identifier[name="MaybeMockedDeep"], Identifier[name="MaybeMocked"]):has(StringLiteral[value="jest-mock"])', (node) => {
26
+ const text = node.getText();
27
+ return (text
28
+ // MaybeMockedDeep and MaybeMocked now are exported as Mocked and MockedShallow
29
+ .replace('MaybeMockedDeep', 'Mocked')
30
+ .replace('MaybeMocked', 'MockedShallow'));
31
+ });
32
+ tree.write(filePath, updatedContent);
33
+ }
34
+ exports.updateJestMockTypes = updateJestMockTypes;
35
+ function updateJestMocked(tree, filePath) {
36
+ const contents = tree.read(filePath, 'utf-8');
37
+ const jestGlobalNodes = tsquery_1.tsquery.query(contents, ':matches(ImportDeclaration, VariableStatement):has(Identifier[name="jest"]):has(StringLiteral[value="@jest/globals"])');
38
+ // this only applies if using jest from @jest/globals
39
+ if (jestGlobalNodes.length === 0) {
40
+ return;
41
+ }
42
+ const updatedJestMockTypes = tsquery_1.tsquery.replace(contents, 'CallExpression:has(Identifier[name="jest"]):has(Identifier[name="mocked"])', (node) => {
43
+ if (node.arguments.length === 2 &&
44
+ node.getText().startsWith('jest.mocked(')) {
45
+ const text = node.getText();
46
+ // jest.mocked(someObject, true); => jest.mocked(someObject);
47
+ if (node.arguments[1].getText() === 'true') {
48
+ return text.replace(/,\s*true/g, '');
49
+ }
50
+ // jest.mocked(someObject, false); => jest.mocked(someObject, {shallow: true});
51
+ // opt into the new behavior unless explicitly opting out
52
+ if (node.arguments[1].getText() === 'false') {
53
+ return text.replace('false', '{shallow: true}');
54
+ }
55
+ }
56
+ });
57
+ tree.write(filePath, updatedJestMockTypes);
58
+ }
59
+ exports.updateJestMocked = updateJestMocked;
60
+ exports.default = updateTestsJest29;
@@ -0,0 +1,2 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export default function replacePackage(tree: Tree): Promise<void>;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const devkit_1 = require("@nx/devkit");
4
+ const replace_package_1 = require("@nx/devkit/src/utils/replace-package");
5
+ async function replacePackage(tree) {
6
+ await (0, replace_package_1.replaceNrwlPackageWithNxPackage)(tree, '@nrwl/jest', '@nx/jest');
7
+ await (0, devkit_1.formatFiles)(tree);
8
+ }
9
+ exports.default = replacePackage;
@@ -0,0 +1,3 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export declare function addTestSetupToIgnoredInputs(tree: Tree): Promise<void>;
3
+ export default addTestSetupToIgnoredInputs;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addTestSetupToIgnoredInputs = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ async function addTestSetupToIgnoredInputs(tree) {
6
+ const nxJson = (0, devkit_1.readNxJson)(tree);
7
+ if (!nxJson) {
8
+ return;
9
+ }
10
+ if (nxJson.namedInputs?.production &&
11
+ !nxJson.namedInputs.production.includes('!{projectRoot}/src/test-setup.[jt]s')) {
12
+ nxJson.namedInputs.production.push('!{projectRoot}/src/test-setup.[jt]s');
13
+ (0, devkit_1.updateNxJson)(tree, nxJson);
14
+ }
15
+ await (0, devkit_1.formatFiles)(tree);
16
+ }
17
+ exports.addTestSetupToIgnoredInputs = addTestSetupToIgnoredInputs;
18
+ exports.default = addTestSetupToIgnoredInputs;
@@ -0,0 +1,2 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export default function update(tree: Tree): Promise<void>;
@@ -0,0 +1,117 @@
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 project_configuration_utils_1 = require("nx/src/project-graph/utils/project-configuration-utils");
6
+ async function update(tree) {
7
+ const nxJson = (0, devkit_1.readNxJson)(tree);
8
+ // Don't override anything if there are already target defaults for jest
9
+ if (nxJson.targetDefaults?.['@nx/jest:jest']) {
10
+ return;
11
+ }
12
+ nxJson.targetDefaults ??= {};
13
+ /**
14
+ * A set of targets which does not use any other executors
15
+ */
16
+ const jestTargets = new Set();
17
+ const graph = await (0, devkit_1.createProjectGraphAsync)();
18
+ (0, executor_options_utils_1.forEachExecutorOptionsInGraph)(graph, '@nx/jest:jest', (value, proj, targetName) => {
19
+ jestTargets.add(targetName);
20
+ });
21
+ // Workspace does not use jest?
22
+ if (jestTargets.size === 0) {
23
+ return;
24
+ }
25
+ // Use the project graph so targets which are inferred are considered
26
+ const projects = graph.nodes;
27
+ const projectMap = (0, devkit_1.getProjects)(tree);
28
+ const jestDefaults = (nxJson.targetDefaults['@nx/jest:jest'] = {});
29
+ // All jest targets have the same name
30
+ if (jestTargets.size === 1) {
31
+ const targetName = Array.from(jestTargets)[0];
32
+ if (nxJson.targetDefaults[targetName]) {
33
+ Object.assign(jestDefaults, nxJson.targetDefaults[targetName]);
34
+ }
35
+ }
36
+ jestDefaults.cache ??= true;
37
+ const inputs = ['default'];
38
+ inputs.push(nxJson.namedInputs?.production ? '^production' : '^default');
39
+ if (tree.exists('jest.preset.js')) {
40
+ inputs.push('{workspaceRoot}/jest.preset.js');
41
+ }
42
+ jestDefaults.inputs ??= inputs;
43
+ // Remember if there were already defaults so we don't assume the executor default
44
+ const passWithNoTestsPreviouslyInDefaults = jestDefaults.options?.passWithNoTests !== undefined;
45
+ const ciCiPreviouslyInDefaults = jestDefaults.configurations?.ci?.ci !== undefined;
46
+ const ciCodeCoveragePreviouslyInDefaults = jestDefaults.configurations?.ci?.codeCoverage !== undefined;
47
+ jestDefaults.options ??= {};
48
+ jestDefaults.options.passWithNoTests ??= true;
49
+ jestDefaults.configurations ??= {};
50
+ jestDefaults.configurations.ci ??= {};
51
+ jestDefaults.configurations.ci.ci ??= true;
52
+ jestDefaults.configurations.ci.codeCoverage ??= true;
53
+ // Cleanup old target defaults
54
+ for (const [targetDefaultKey, targetDefault] of Object.entries(nxJson.targetDefaults)) {
55
+ if (!isTargetDefaultUsed(targetDefault, nxJson.targetDefaults, projects, projectMap)) {
56
+ delete nxJson.targetDefaults[targetDefaultKey];
57
+ }
58
+ }
59
+ (0, devkit_1.updateNxJson)(tree, nxJson);
60
+ (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nx/jest:jest', (value, proj, targetName, configuration) => {
61
+ const projConfig = projectMap.get(proj);
62
+ if (!configuration) {
63
+ // Options
64
+ if (value.passWithNoTests === jestDefaults.options.passWithNoTests) {
65
+ delete projConfig.targets[targetName].options.passWithNoTests;
66
+ }
67
+ else if (!passWithNoTestsPreviouslyInDefaults) {
68
+ projConfig.targets[targetName].options.passWithNoTests ??= false;
69
+ }
70
+ if (Object.keys(projConfig.targets[targetName].options).length === 0) {
71
+ delete projConfig.targets[targetName].options;
72
+ }
73
+ }
74
+ else if (configuration === 'ci') {
75
+ // CI Config
76
+ if (value.ci === jestDefaults.configurations.ci.ci) {
77
+ delete projConfig.targets[targetName].configurations.ci.ci;
78
+ }
79
+ else if (ciCiPreviouslyInDefaults) {
80
+ projConfig.targets[targetName].configurations.ci.ci ??= false;
81
+ }
82
+ if (value.codeCoverage === jestDefaults.configurations.ci.codeCoverage) {
83
+ delete projConfig.targets[targetName].configurations.ci.codeCoverage;
84
+ }
85
+ else if (ciCodeCoveragePreviouslyInDefaults) {
86
+ projConfig.targets[targetName].configurations.ci.codeCoverage ??=
87
+ false;
88
+ }
89
+ if (Object.keys(projConfig.targets[targetName].configurations.ci)
90
+ .length === 0) {
91
+ delete projConfig.targets[targetName].configurations.ci;
92
+ }
93
+ if (Object.keys(projConfig.targets[targetName].configurations).length ===
94
+ 0) {
95
+ delete projConfig.targets[targetName].configurations;
96
+ }
97
+ }
98
+ (0, devkit_1.updateProjectConfiguration)(tree, proj, projConfig);
99
+ });
100
+ await (0, devkit_1.formatFiles)(tree);
101
+ }
102
+ exports.default = update;
103
+ /**
104
+ * Checks every target on every project to see if one of them uses the target default
105
+ */
106
+ function isTargetDefaultUsed(targetDefault, targetDefaults, projects, projectMap) {
107
+ for (const p of Object.values(projects)) {
108
+ for (const targetName in p.data?.targets ?? {}) {
109
+ if ((0, project_configuration_utils_1.readTargetDefaultsForTarget)(targetName, targetDefaults,
110
+ // It might seem like we should use the graph here too but we don't want to pass an executor which was processed in the graph
111
+ projectMap.get(p.name)?.targets?.[targetName]?.executor) === targetDefault) {
112
+ return true;
113
+ }
114
+ }
115
+ }
116
+ return false;
117
+ }
@@ -0,0 +1,6 @@
1
+ import { CreateDependencies, CreateNodes } from '@nx/devkit';
2
+ export interface JestPluginOptions {
3
+ targetName?: string;
4
+ }
5
+ export declare const createDependencies: CreateDependencies;
6
+ export declare const createNodes: CreateNodes<JestPluginOptions>;
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNodes = exports.createDependencies = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const path_1 = require("path");
6
+ const project_configuration_utils_1 = require("nx/src/project-graph/utils/project-configuration-utils");
7
+ const get_named_inputs_1 = require("@nx/devkit/src/utils/get-named-inputs");
8
+ const fs_1 = require("fs");
9
+ const jest_config_1 = require("jest-config");
10
+ const cache_directory_1 = require("nx/src/utils/cache-directory");
11
+ const calculate_hash_for_create_nodes_1 = require("@nx/devkit/src/utils/calculate-hash-for-create-nodes");
12
+ const package_json_workspaces_1 = require("nx/src/plugins/package-json-workspaces");
13
+ const globs_1 = require("nx/src/utils/globs");
14
+ const minimatch_1 = require("minimatch");
15
+ const cachePath = (0, path_1.join)(cache_directory_1.projectGraphCacheDirectory, 'jest.hash');
16
+ const targetsCache = (0, fs_1.existsSync)(cachePath) ? readTargetsCache() : {};
17
+ const calculatedTargets = {};
18
+ function readTargetsCache() {
19
+ return (0, devkit_1.readJsonFile)(cachePath);
20
+ }
21
+ function writeTargetsToCache(targets) {
22
+ (0, devkit_1.writeJsonFile)(cachePath, targets);
23
+ }
24
+ const createDependencies = () => {
25
+ writeTargetsToCache(calculatedTargets);
26
+ return [];
27
+ };
28
+ exports.createDependencies = createDependencies;
29
+ exports.createNodes = [
30
+ '**/jest.config.{cjs,mjs,js,cts,mts,ts}',
31
+ async (configFilePath, options, context) => {
32
+ const projectRoot = (0, path_1.dirname)(configFilePath);
33
+ const packageManagerWorkspacesGlob = (0, globs_1.combineGlobPatterns)((0, package_json_workspaces_1.getGlobPatternsFromPackageManagerWorkspaces)(context.workspaceRoot));
34
+ // Do not create a project if package.json and project.json isn't there.
35
+ const siblingFiles = (0, fs_1.readdirSync)((0, path_1.join)(context.workspaceRoot, projectRoot));
36
+ if (!siblingFiles.includes('package.json') &&
37
+ !siblingFiles.includes('project.json')) {
38
+ return {};
39
+ }
40
+ else if (!siblingFiles.includes('project.json') &&
41
+ siblingFiles.includes('package.json')) {
42
+ const path = (0, devkit_1.joinPathFragments)(projectRoot, 'package.json');
43
+ const isPackageJsonProject = (0, minimatch_1.minimatch)(path, packageManagerWorkspacesGlob);
44
+ if (!isPackageJsonProject) {
45
+ return {};
46
+ }
47
+ }
48
+ const jestConfigContent = (0, fs_1.readFileSync)((0, path_1.resolve)(context.workspaceRoot, configFilePath), 'utf-8');
49
+ if (jestConfigContent.includes('getJestProjectsAsync()')) {
50
+ // The `getJestProjectsAsync` function uses the project graph, which leads to a
51
+ // circular dependency. We can skip this since it's no intended to be used for
52
+ // an Nx project.
53
+ return {};
54
+ }
55
+ options = normalizeOptions(options);
56
+ const hash = (0, calculate_hash_for_create_nodes_1.calculateHashForCreateNodes)(projectRoot, options, context);
57
+ const targets = targetsCache[hash] ??
58
+ (await buildJestTargets(configFilePath, projectRoot, options, context));
59
+ calculatedTargets[hash] = targets;
60
+ return {
61
+ projects: {
62
+ [projectRoot]: {
63
+ root: projectRoot,
64
+ targets: targets,
65
+ },
66
+ },
67
+ };
68
+ },
69
+ ];
70
+ async function buildJestTargets(configFilePath, projectRoot, options, context) {
71
+ const config = await (0, jest_config_1.readConfig)({
72
+ _: [],
73
+ $0: undefined,
74
+ }, (0, path_1.resolve)(context.workspaceRoot, configFilePath));
75
+ const targetDefaults = (0, project_configuration_utils_1.readTargetDefaultsForTarget)(options.targetName, context.nxJsonConfiguration.targetDefaults, 'nx:run-commands');
76
+ const namedInputs = (0, get_named_inputs_1.getNamedInputs)(projectRoot, context);
77
+ const targets = {};
78
+ const target = (targets[options.targetName] = {
79
+ command: 'jest',
80
+ options: {
81
+ cwd: projectRoot,
82
+ },
83
+ });
84
+ if (!targetDefaults?.cache) {
85
+ target.cache = true;
86
+ }
87
+ if (!targetDefaults?.inputs) {
88
+ target.inputs = getInputs(namedInputs);
89
+ }
90
+ if (!targetDefaults?.outputs) {
91
+ target.outputs = getOutputs(projectRoot, config, context);
92
+ }
93
+ return targets;
94
+ }
95
+ function getInputs(namedInputs) {
96
+ return [
97
+ ...('production' in namedInputs
98
+ ? ['default', '^production']
99
+ : ['default', '^default']),
100
+ {
101
+ externalDependencies: ['jest'],
102
+ },
103
+ ];
104
+ }
105
+ function getOutputs(projectRoot, { globalConfig }, context) {
106
+ function getOutput(path) {
107
+ const relativePath = (0, path_1.relative)((0, path_1.join)(context.workspaceRoot, projectRoot), path);
108
+ if (relativePath.startsWith('..')) {
109
+ return (0, path_1.join)('{workspaceRoot}', (0, path_1.join)(projectRoot, relativePath));
110
+ }
111
+ else {
112
+ return (0, path_1.join)('{projectRoot}', relativePath);
113
+ }
114
+ }
115
+ const outputs = [];
116
+ for (const outputOption of [
117
+ globalConfig.coverageDirectory,
118
+ globalConfig.outputFile,
119
+ ]) {
120
+ if (outputOption) {
121
+ outputs.push(getOutput(outputOption));
122
+ }
123
+ }
124
+ return outputs;
125
+ }
126
+ function normalizeOptions(options) {
127
+ options ??= {};
128
+ options.targetName ??= 'test';
129
+ return options;
130
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * match testing file based on their name file
3
+ */
4
+ export declare const TEST_FILE_PATTERN: RegExp;
5
+ /**
6
+ * Match right hand side of `export default` or `module.exports` = statements
7
+ */
8
+ export declare const TS_QUERY_JEST_CONFIG_PREFIX = ":matches(ExportAssignment, BinaryExpression:has(Identifier[name=\"module\"]):has(Identifier[name=\"exports\"]))";
9
+ export declare function addTransformerToConfig(configContents: string, transformer: string): string;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addTransformerToConfig = exports.TS_QUERY_JEST_CONFIG_PREFIX = exports.TEST_FILE_PATTERN = void 0;
4
+ const tsquery_1 = require("@phenomnomnominal/tsquery");
5
+ /**
6
+ * match testing file based on their name file
7
+ */
8
+ exports.TEST_FILE_PATTERN = new RegExp('.*(spec|test).[jt]sx?$');
9
+ /**
10
+ * Match right hand side of `export default` or `module.exports` = statements
11
+ */
12
+ exports.TS_QUERY_JEST_CONFIG_PREFIX = ':matches(ExportAssignment, BinaryExpression:has(Identifier[name="module"]):has(Identifier[name="exports"]))';
13
+ function addTransformerToConfig(configContents, transformer) {
14
+ // TODO make sure there isn't an existing matching transformer regex
15
+ const transformerConfig = tsquery_1.tsquery.query(configContents, `${exports.TS_QUERY_JEST_CONFIG_PREFIX} > ObjectLiteralExpression PropertyAssignment:has(Identifier[name="transform"])`);
16
+ if (transformerConfig.length === 0) {
17
+ return tsquery_1.tsquery.replace(configContents, `${exports.TS_QUERY_JEST_CONFIG_PREFIX} > ObjectLiteralExpression`, (node) => {
18
+ return `{
19
+ ${node.properties.map((p) => p.getText()).join(',\n')},
20
+ transform: { ${transformer} }
21
+ }`;
22
+ });
23
+ }
24
+ return tsquery_1.tsquery.replace(configContents, `${exports.TS_QUERY_JEST_CONFIG_PREFIX} > ObjectLiteralExpression PropertyAssignment:has(Identifier[name="transform"])`, (node) => {
25
+ const transformObject = node.initializer;
26
+ const transformProperties = transformObject.properties
27
+ .map((p) => p.getText())
28
+ .join(',\n');
29
+ return `transform: { ${transformer}, ${transformProperties} }`;
30
+ });
31
+ }
32
+ exports.addTransformerToConfig = addTransformerToConfig;
@@ -0,0 +1,3 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export declare function findRootJestConfig(tree: Tree): string | null;
3
+ export declare function findRootJestPreset(tree: Tree): string | null;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findRootJestPreset = exports.findRootJestConfig = void 0;
4
+ function findRootJestConfig(tree) {
5
+ if (tree.exists('jest.config.js')) {
6
+ return 'jest.config.js';
7
+ }
8
+ if (tree.exists('jest.config.ts')) {
9
+ return 'jest.config.ts';
10
+ }
11
+ return null;
12
+ }
13
+ exports.findRootJestConfig = findRootJestConfig;
14
+ function findRootJestPreset(tree) {
15
+ if (tree.exists('jest.preset.js')) {
16
+ return 'jest.preset.js';
17
+ }
18
+ if (tree.exists('jest.preset.cjs')) {
19
+ return 'jest.preset.cjs';
20
+ }
21
+ return null;
22
+ }
23
+ exports.findRootJestPreset = findRootJestPreset;
@@ -0,0 +1,17 @@
1
+ import type * as ts from 'typescript';
2
+ import { Tree } from '@nx/devkit';
3
+ import { Config } from '@jest/types';
4
+ export declare function addOrUpdateProperty(tree: Tree, object: ts.ObjectLiteralExpression, properties: string[], value: unknown, path: string): any[];
5
+ export declare function removeProperty(object: ts.ObjectLiteralExpression, properties: string[]): ts.PropertyAssignment | null;
6
+ /**
7
+ * Should be used to get the jest config object as AST
8
+ */
9
+ export declare function jestConfigObjectAst(fileContent: string): ts.ObjectLiteralExpression;
10
+ /**
11
+ * Returns the jest config object
12
+ * @param host
13
+ * @param path
14
+ */
15
+ export declare function jestConfigObject(host: Tree, path: string): Partial<Config.InitialOptions> & {
16
+ [index: string]: any;
17
+ };