@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,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createFiles = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const path_1 = require("path");
6
+ function createFiles(tree, options, presetExt) {
7
+ const projectConfig = (0, devkit_1.readProjectConfiguration)(tree, options.project);
8
+ const filesFolder = options.setupFile === 'angular' ? '../files-angular' : '../files';
9
+ let transformer;
10
+ let transformerOptions = null;
11
+ if (options.compiler === 'babel' || options.babelJest) {
12
+ transformer = 'babel-jest';
13
+ }
14
+ else if (options.compiler === 'swc') {
15
+ transformer = '@swc/jest';
16
+ if (options.supportTsx) {
17
+ transformerOptions =
18
+ "{ jsc: { parser: { syntax: 'typescript', tsx: true }, transform: { react: { runtime: 'automatic' } } } }";
19
+ }
20
+ }
21
+ else {
22
+ transformer = 'ts-jest';
23
+ transformerOptions = "{ tsconfig: '<rootDir>/tsconfig.spec.json' }";
24
+ }
25
+ (0, devkit_1.generateFiles)(tree, (0, path_1.join)(__dirname, filesFolder), projectConfig.root, {
26
+ tmpl: '',
27
+ ...options,
28
+ // jsdom is the default
29
+ testEnvironment: options.testEnvironment === 'none' || options.testEnvironment === 'jsdom'
30
+ ? ''
31
+ : options.testEnvironment,
32
+ transformer,
33
+ transformerOptions,
34
+ js: !!options.js,
35
+ rootProject: options.rootProject,
36
+ projectRoot: options.rootProject ? options.project : projectConfig.root,
37
+ offsetFromRoot: (0, devkit_1.offsetFromRoot)(projectConfig.root),
38
+ presetExt,
39
+ });
40
+ if (options.setupFile === 'none') {
41
+ tree.delete((0, path_1.join)(projectConfig.root, './src/test-setup.ts'));
42
+ }
43
+ if (options.js) {
44
+ tree.rename((0, path_1.join)(projectConfig.root, 'jest.config.ts'), (0, path_1.join)(projectConfig.root, 'jest.config.js'));
45
+ }
46
+ }
47
+ exports.createFiles = createFiles;
@@ -0,0 +1,3 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ import type { NormalizedJestProjectSchema } from '../schema';
3
+ export declare function createJestConfig(tree: Tree, options: Partial<NormalizedJestProjectSchema>, presetExt: 'cjs' | 'js'): Promise<void>;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createJestConfig = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const project_configuration_utils_1 = require("nx/src/project-graph/utils/project-configuration-utils");
6
+ const find_root_jest_files_1 = require("../../../utils/config/find-root-jest-files");
7
+ async function createJestConfig(tree, options, presetExt) {
8
+ if (!tree.exists(`jest.preset.${presetExt}`)) {
9
+ // preset is always js file.
10
+ tree.write(`jest.preset.${presetExt}`, `
11
+ const nxPreset = require('@nx/jest/preset').default;
12
+
13
+ module.exports = { ...nxPreset }`);
14
+ }
15
+ if (options.rootProject) {
16
+ // we don't want any config to be made because the `configurationGenerator` will do it.
17
+ // will copy the template config file
18
+ return;
19
+ }
20
+ const rootJestPath = (0, find_root_jest_files_1.findRootJestConfig)(tree);
21
+ if (!rootJestPath) {
22
+ // if there's not root jest config, we will create one and return
23
+ // this can happen when:
24
+ // - root jest config was renamed => in which case there is migration needed
25
+ // - root project didn't have jest setup => again, no migration is needed
26
+ generateGlobalConfig(tree, options.js);
27
+ return;
28
+ }
29
+ if (tree.exists(rootJestPath)) {
30
+ // moving from root project config to monorepo-style config
31
+ const { nodes: projects } = await (0, devkit_1.createProjectGraphAsync)();
32
+ const projectConfigurations = Object.values(projects);
33
+ const rootProject = projectConfigurations.find((projectNode) => projectNode.data?.root === '.');
34
+ // root project might have been removed,
35
+ // if it's missing there's nothing to migrate
36
+ if (rootProject) {
37
+ const jestTarget = Object.entries(rootProject.data?.targets ?? {}).find(([_, t]) => ((t?.executor === '@nx/jest:jest' ||
38
+ t?.executor === '@nrwl/jest:jest') &&
39
+ t?.options?.jestConfig === rootJestPath) ||
40
+ (t?.executor === 'nx:run-commands' && t?.options?.command === 'jest'));
41
+ if (!jestTarget) {
42
+ return;
43
+ }
44
+ const [jestTargetName, jestTargetConfigInGraph] = jestTarget;
45
+ // if root project doesn't have jest target, there's nothing to migrate
46
+ const rootProjectConfig = (0, devkit_1.readProjectConfiguration)(tree, rootProject.name);
47
+ if (rootProjectConfig.targets?.['test']?.executor === 'nx:run-commands'
48
+ ? rootProjectConfig.targets?.['test']?.command !== 'jest'
49
+ : rootProjectConfig.targets?.['test']?.options?.jestConfig !==
50
+ rootJestPath) {
51
+ // Jest target has already been updated
52
+ return;
53
+ }
54
+ const jestProjectConfig = `jest.config.${rootProjectConfig.projectType === 'application' ? 'app' : 'lib'}.${options.js ? 'js' : 'ts'}`;
55
+ tree.rename(rootJestPath, jestProjectConfig);
56
+ const nxJson = (0, devkit_1.readNxJson)(tree);
57
+ const targetDefaults = (0, project_configuration_utils_1.readTargetDefaultsForTarget)(jestTargetName, nxJson.targetDefaults, jestTargetConfigInGraph.executor);
58
+ const target = (rootProjectConfig.targets[jestTargetName] ??=
59
+ jestTargetConfigInGraph.executor === 'nx:run-commands'
60
+ ? { command: `jest --config ${jestProjectConfig}` }
61
+ : {
62
+ executor: jestTargetConfigInGraph.executor,
63
+ options: {},
64
+ });
65
+ if (target.executor === '@nx/jest:jest') {
66
+ target.options.jestConfig = jestProjectConfig;
67
+ }
68
+ if (targetDefaults?.cache === undefined) {
69
+ target.cache = jestTargetConfigInGraph.cache;
70
+ }
71
+ if (targetDefaults?.inputs === undefined) {
72
+ target.inputs = jestTargetConfigInGraph.inputs;
73
+ }
74
+ if (targetDefaults?.outputs === undefined) {
75
+ target.outputs = jestTargetConfigInGraph.outputs;
76
+ }
77
+ if (targetDefaults?.dependsOn === undefined) {
78
+ target.dependsOn = jestTargetConfigInGraph.dependsOn;
79
+ }
80
+ (0, devkit_1.updateProjectConfiguration)(tree, rootProject.name, rootProjectConfig);
81
+ // generate new global config as it was move to project config or is missing
82
+ generateGlobalConfig(tree, options.js);
83
+ }
84
+ }
85
+ }
86
+ exports.createJestConfig = createJestConfig;
87
+ function generateGlobalConfig(tree, isJS) {
88
+ const contents = isJS
89
+ ? (0, devkit_1.stripIndents) `
90
+ const { getJestProjectsAsync } = require('@nx/jest');
91
+
92
+ module.exports = async () => ({
93
+ projects: await getJestProjectsAsync()
94
+ });`
95
+ : (0, devkit_1.stripIndents) `
96
+ import { getJestProjectsAsync } from '@nx/jest';
97
+
98
+ export default async () => ({
99
+ projects: await getJestProjectsAsync()
100
+ });`;
101
+ tree.write(`jest.config.${isJS ? 'js' : 'ts'}`, contents);
102
+ }
@@ -0,0 +1,3 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ import type { NormalizedJestProjectSchema } from '../schema';
3
+ export declare function ensureDependencies(tree: Tree, options: Partial<NormalizedJestProjectSchema>): import("@nx/devkit").GeneratorCallback;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ensureDependencies = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const versions_1 = require("../../../utils/versions");
6
+ function ensureDependencies(tree, options) {
7
+ const dependencies = {
8
+ tslib: versions_1.tslibVersion,
9
+ };
10
+ const devDeps = {
11
+ // because the default jest-preset uses ts-jest,
12
+ // jest will throw an error if it's not installed
13
+ // even if not using it in overriding transformers
14
+ 'ts-jest': versions_1.tsJestVersion,
15
+ };
16
+ if (options.testEnvironment !== 'none') {
17
+ devDeps[`jest-environment-${options.testEnvironment}`] = versions_1.jestVersion;
18
+ }
19
+ if (!options.js) {
20
+ devDeps['ts-node'] = versions_1.tsNodeVersion;
21
+ devDeps['@types/jest'] = versions_1.jestTypesVersion;
22
+ devDeps['@types/node'] = versions_1.typesNodeVersion;
23
+ }
24
+ if (options.compiler === 'babel' || options.babelJest) {
25
+ devDeps['babel-jest'] = versions_1.babelJestVersion;
26
+ // in some cases @nx/js will not already be present i.e. node only projects
27
+ devDeps['@nx/js'] = versions_1.nxVersion;
28
+ }
29
+ else if (options.compiler === 'swc') {
30
+ devDeps['@swc/jest'] = versions_1.swcJestVersion;
31
+ }
32
+ return (0, devkit_1.addDependenciesToPackageJson)(tree, dependencies, devDeps);
33
+ }
34
+ exports.ensureDependencies = ensureDependencies;
@@ -0,0 +1,3 @@
1
+ import { NormalizedJestProjectSchema } from '../schema';
2
+ import { Tree } from '@nx/devkit';
3
+ export declare function updateJestConfig(host: Tree, options: NormalizedJestProjectSchema): void;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateJestConfig = void 0;
4
+ const find_root_jest_files_1 = require("../../../utils/config/find-root-jest-files");
5
+ const update_config_1 = require("../../../utils/config/update-config");
6
+ const devkit_1 = require("@nx/devkit");
7
+ function isUsingUtilityFunction(host) {
8
+ const rootConfig = (0, find_root_jest_files_1.findRootJestConfig)(host);
9
+ if (!rootConfig) {
10
+ return false;
11
+ }
12
+ const rootConfigContent = host.read(rootConfig, 'utf-8');
13
+ return (rootConfigContent.includes('getJestProjects()') ||
14
+ rootConfigContent.includes('getJestProjectsAsync()'));
15
+ }
16
+ function updateJestConfig(host, options) {
17
+ if (isUsingUtilityFunction(host)) {
18
+ return;
19
+ }
20
+ const project = (0, devkit_1.readProjectConfiguration)(host, options.project);
21
+ const rootConfig = (0, find_root_jest_files_1.findRootJestConfig)(host);
22
+ if (rootConfig) {
23
+ (0, update_config_1.addPropertyToJestConfig)(host, (0, find_root_jest_files_1.findRootJestConfig)(host), 'projects', `<rootDir>/${project.root}`);
24
+ }
25
+ }
26
+ exports.updateJestConfig = updateJestConfig;
@@ -0,0 +1,3 @@
1
+ import { NormalizedJestProjectSchema } from '../schema';
2
+ import { Tree } from '@nx/devkit';
3
+ export declare function updateTsConfig(host: Tree, options: NormalizedJestProjectSchema): void;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateTsConfig = void 0;
4
+ const path_1 = require("path");
5
+ const devkit_1 = require("@nx/devkit");
6
+ function updateTsConfig(host, options) {
7
+ const projectConfig = (0, devkit_1.readProjectConfiguration)(host, options.project);
8
+ if (!host.exists((0, path_1.join)(projectConfig.root, 'tsconfig.json'))) {
9
+ throw new Error(`Expected ${(0, path_1.join)(projectConfig.root, 'tsconfig.json')} to exist. Please create one.`);
10
+ }
11
+ (0, devkit_1.updateJson)(host, (0, path_1.join)(projectConfig.root, 'tsconfig.json'), (json) => {
12
+ if (json.references &&
13
+ !json.references.some((r) => r.path === './tsconfig.spec.json')) {
14
+ json.references.push({
15
+ path: './tsconfig.spec.json',
16
+ });
17
+ }
18
+ return json;
19
+ });
20
+ }
21
+ exports.updateTsConfig = updateTsConfig;
@@ -0,0 +1,2 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ export declare function updateVsCodeRecommendedExtensions(host: Tree): void;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateVsCodeRecommendedExtensions = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ function updateVsCodeRecommendedExtensions(host) {
6
+ if (!host.exists('.vscode/extensions.json')) {
7
+ return;
8
+ }
9
+ (0, devkit_1.updateJson)(host, '.vscode/extensions.json', (json) => {
10
+ json.recommendations = json.recommendations || [];
11
+ const extension = 'firsttris.vscode-jest-runner';
12
+ if (!json.recommendations.includes(extension)) {
13
+ json.recommendations.push(extension);
14
+ }
15
+ return json;
16
+ });
17
+ }
18
+ exports.updateVsCodeRecommendedExtensions = updateVsCodeRecommendedExtensions;
@@ -0,0 +1,3 @@
1
+ import { NormalizedJestProjectSchema } from '../schema';
2
+ import { Tree } from '@nx/devkit';
3
+ export declare function updateWorkspace(tree: Tree, options: NormalizedJestProjectSchema): void;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateWorkspace = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ function updateWorkspace(tree, options) {
6
+ const projectConfig = (0, devkit_1.readProjectConfiguration)(tree, options.project);
7
+ if (!projectConfig.targets) {
8
+ projectConfig.targets = {};
9
+ }
10
+ projectConfig.targets[options.targetName] = {
11
+ executor: '@nx/jest:jest',
12
+ outputs: [
13
+ options.rootProject
14
+ ? (0, devkit_1.joinPathFragments)('{workspaceRoot}', 'coverage', '{projectName}')
15
+ : (0, devkit_1.joinPathFragments)('{workspaceRoot}', 'coverage', '{projectRoot}'),
16
+ ],
17
+ options: {
18
+ jestConfig: (0, devkit_1.joinPathFragments)((0, devkit_1.normalizePath)(projectConfig.root), `jest.config.${options.js ? 'js' : 'ts'}`),
19
+ },
20
+ };
21
+ (0, devkit_1.updateProjectConfiguration)(tree, options.project, projectConfig);
22
+ }
23
+ exports.updateWorkspace = updateWorkspace;
@@ -0,0 +1,31 @@
1
+ export interface JestProjectSchema {
2
+ project: string;
3
+ targetName?: string;
4
+ supportTsx?: boolean;
5
+ /**
6
+ * @deprecated use setupFile instead
7
+ */
8
+ skipSetupFile?: boolean;
9
+ setupFile?: 'angular' | 'web-components' | 'none';
10
+ skipSerializers?: boolean;
11
+ testEnvironment?: 'node' | 'jsdom' | 'none';
12
+ /**
13
+ * @deprecated use compiler: "babel" instead
14
+ */
15
+ babelJest?: boolean;
16
+ skipFormat?: boolean;
17
+
18
+ addPlugin?: boolean;
19
+ compiler?: 'tsc' | 'babel' | 'swc';
20
+ skipPackageJson?: boolean;
21
+ js?: boolean;
22
+
23
+ /**
24
+ * @internal
25
+ */
26
+ addExplicitTargets?: boolean;
27
+ }
28
+
29
+ export type NormalizedJestProjectSchema = JestProjectSchema & {
30
+ rootProject: boolean;
31
+ };
@@ -0,0 +1,80 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "$id": "NxJestProject",
4
+ "cli": "nx",
5
+ "title": "Add Jest Configuration to a project",
6
+ "description": "Add Jest Configuration to a project.",
7
+ "type": "object",
8
+ "properties": {
9
+ "project": {
10
+ "type": "string",
11
+ "description": "The name of the project.",
12
+ "$default": {
13
+ "$source": "projectName"
14
+ },
15
+ "x-priority": "important"
16
+ },
17
+ "skipSetupFile": {
18
+ "type": "boolean",
19
+ "description": "Skips the setup file required for angular.",
20
+ "default": false,
21
+ "x-deprecated": "Use `--setup-file` instead."
22
+ },
23
+ "setupFile": {
24
+ "type": "string",
25
+ "enum": ["none", "angular", "web-components"],
26
+ "description": "The setup file to be generated.",
27
+ "default": "none",
28
+ "x-priority": "important"
29
+ },
30
+ "skipSerializers": {
31
+ "type": "boolean",
32
+ "description": "Skips the serializers required to snapshot angular templates.",
33
+ "default": false
34
+ },
35
+ "supportTsx": {
36
+ "type": "boolean",
37
+ "description": "Setup `tsx` support.",
38
+ "default": false,
39
+ "x-priority": "important"
40
+ },
41
+ "testEnvironment": {
42
+ "type": "string",
43
+ "enum": ["jsdom", "node", "none"],
44
+ "description": "The test environment for jest.",
45
+ "default": "jsdom",
46
+ "x-priority": "important"
47
+ },
48
+ "compiler": {
49
+ "type": "string",
50
+ "enum": ["tsc", "babel", "swc"],
51
+ "description": "The compiler to use for source and tests.",
52
+ "default": "tsc"
53
+ },
54
+ "babelJest": {
55
+ "type": "boolean",
56
+ "alias": "babel-jest",
57
+ "description": "Use `babel-jest` instead of `ts-jest`.",
58
+ "x-deprecated": "Use `--compiler=babel` instead.",
59
+ "default": false
60
+ },
61
+ "skipFormat": {
62
+ "description": "Skip formatting files",
63
+ "type": "boolean",
64
+ "default": false,
65
+ "x-priority": "internal"
66
+ },
67
+ "skipPackageJson": {
68
+ "type": "boolean",
69
+ "default": false,
70
+ "description": "Do not add dependencies to `package.json`.",
71
+ "x-priority": "internal"
72
+ },
73
+ "js": {
74
+ "type": "boolean",
75
+ "default": false,
76
+ "description": "Use JavaScript instead of TypeScript for config files"
77
+ }
78
+ },
79
+ "required": []
80
+ }
@@ -0,0 +1,5 @@
1
+ import { type GeneratorCallback, type Tree } from '@nx/devkit';
2
+ import type { JestInitSchema } from './schema';
3
+ export declare function jestInitGenerator(tree: Tree, options: JestInitSchema): Promise<GeneratorCallback>;
4
+ export declare function jestInitGeneratorInternal(tree: Tree, options: JestInitSchema): Promise<GeneratorCallback>;
5
+ export default jestInitGenerator;
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.jestInitGeneratorInternal = exports.jestInitGenerator = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const update_package_scripts_1 = require("@nx/devkit/src/utils/update-package-scripts");
6
+ const plugin_1 = require("../../plugins/plugin");
7
+ const versions_1 = require("../../utils/versions");
8
+ const is_preset_cjs_1 = require("../../utils/config/is-preset-cjs");
9
+ function addPlugin(tree) {
10
+ const nxJson = (0, devkit_1.readNxJson)(tree);
11
+ nxJson.plugins ??= [];
12
+ if (!nxJson.plugins.some((p) => typeof p === 'string'
13
+ ? p === '@nx/jest/plugin'
14
+ : p.plugin === '@nx/jest/plugin')) {
15
+ nxJson.plugins.push({
16
+ plugin: '@nx/jest/plugin',
17
+ options: {
18
+ targetName: 'test',
19
+ },
20
+ });
21
+ }
22
+ (0, devkit_1.updateNxJson)(tree, nxJson);
23
+ }
24
+ function updateProductionFileSet(tree, presetExt) {
25
+ const nxJson = (0, devkit_1.readNxJson)(tree);
26
+ const productionFileSet = nxJson.namedInputs?.production;
27
+ if (productionFileSet) {
28
+ // This is one of the patterns in the default jest patterns
29
+ productionFileSet.push(
30
+ // Remove spec, test, and snapshots from the production fileset
31
+ '!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)',
32
+ // Remove tsconfig.spec.json
33
+ '!{projectRoot}/tsconfig.spec.json',
34
+ // Remove jest.config.js/ts
35
+ '!{projectRoot}/jest.config.[jt]s',
36
+ // Remove test-setup.js/ts
37
+ // TODO(meeroslav) this should be standardized
38
+ '!{projectRoot}/src/test-setup.[jt]s', '!{projectRoot}/test-setup.[jt]s');
39
+ // Dedupe and set
40
+ nxJson.namedInputs.production = Array.from(new Set(productionFileSet));
41
+ }
42
+ (0, devkit_1.updateNxJson)(tree, nxJson);
43
+ }
44
+ function addJestTargetDefaults(tree, presetEnv) {
45
+ const nxJson = (0, devkit_1.readNxJson)(tree);
46
+ nxJson.targetDefaults ??= {};
47
+ nxJson.targetDefaults['@nx/jest:jest'] ??= {};
48
+ const productionFileSet = nxJson.namedInputs?.production;
49
+ nxJson.targetDefaults['@nx/jest:jest'].cache ??= true;
50
+ // Test targets depend on all their project's sources + production sources of dependencies
51
+ nxJson.targetDefaults['@nx/jest:jest'].inputs ??= [
52
+ 'default',
53
+ productionFileSet ? '^production' : '^default',
54
+ `{workspaceRoot}/jest.preset.${presetEnv}`,
55
+ ];
56
+ nxJson.targetDefaults['@nx/jest:jest'].options ??= {
57
+ passWithNoTests: true,
58
+ };
59
+ nxJson.targetDefaults['@nx/jest:jest'].configurations ??= {
60
+ ci: {
61
+ ci: true,
62
+ codeCoverage: true,
63
+ },
64
+ };
65
+ (0, devkit_1.updateNxJson)(tree, nxJson);
66
+ }
67
+ function updateDependencies(tree, options) {
68
+ return (0, devkit_1.addDependenciesToPackageJson)(tree, {}, {
69
+ '@nx/jest': versions_1.nxVersion,
70
+ jest: versions_1.jestVersion,
71
+ }, undefined, options.keepExistingVersions);
72
+ }
73
+ function jestInitGenerator(tree, options) {
74
+ return jestInitGeneratorInternal(tree, { addPlugin: false, ...options });
75
+ }
76
+ exports.jestInitGenerator = jestInitGenerator;
77
+ async function jestInitGeneratorInternal(tree, options) {
78
+ const nxJson = (0, devkit_1.readNxJson)(tree);
79
+ const addPluginDefault = process.env.NX_ADD_PLUGINS !== 'false' &&
80
+ nxJson.useInferencePlugins !== false;
81
+ options.addPlugin ??= addPluginDefault;
82
+ const presetExt = (0, is_preset_cjs_1.isPresetCjs)(tree) ? 'cjs' : 'js';
83
+ if (!tree.exists('jest.preset.js') && !tree.exists('jest.preset.cjs')) {
84
+ updateProductionFileSet(tree, presetExt);
85
+ if (options.addPlugin) {
86
+ addPlugin(tree);
87
+ }
88
+ else {
89
+ addJestTargetDefaults(tree, presetExt);
90
+ }
91
+ }
92
+ const tasks = [];
93
+ if (!options.skipPackageJson) {
94
+ tasks.push((0, devkit_1.removeDependenciesFromPackageJson)(tree, ['@nx/jest'], []));
95
+ tasks.push(updateDependencies(tree, options));
96
+ }
97
+ if (options.updatePackageScripts) {
98
+ await (0, update_package_scripts_1.updatePackageScripts)(tree, plugin_1.createNodes);
99
+ }
100
+ if (!options.skipFormat) {
101
+ await (0, devkit_1.formatFiles)(tree);
102
+ }
103
+ return (0, devkit_1.runTasksInSerial)(...tasks);
104
+ }
105
+ exports.jestInitGeneratorInternal = jestInitGeneratorInternal;
106
+ exports.default = jestInitGenerator;
@@ -0,0 +1,8 @@
1
+ export interface JestInitSchema {
2
+ skipFormat?: boolean;
3
+ skipPackageJson?: boolean;
4
+ keepExistingVersions?: boolean;
5
+ updatePackageScripts?: boolean;
6
+
7
+ addPlugin?: boolean;
8
+ }
@@ -0,0 +1,35 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "$id": "NxJestInit",
4
+ "cli": "nx",
5
+ "title": "Jest init",
6
+ "description": "Add Jest Configuration to a workspace.",
7
+ "type": "object",
8
+ "properties": {
9
+ "skipFormat": {
10
+ "description": "Skip formatting files.",
11
+ "type": "boolean",
12
+ "default": false,
13
+ "x-priority": "internal"
14
+ },
15
+ "skipPackageJson": {
16
+ "type": "boolean",
17
+ "default": false,
18
+ "description": "Do not add dependencies to `package.json`.",
19
+ "x-priority": "internal"
20
+ },
21
+ "keepExistingVersions": {
22
+ "type": "boolean",
23
+ "x-priority": "internal",
24
+ "description": "Keep existing dependencies versions",
25
+ "default": false
26
+ },
27
+ "updatePackageScripts": {
28
+ "type": "boolean",
29
+ "x-priority": "internal",
30
+ "description": "Update `package.json` scripts with inferred targets",
31
+ "default": false
32
+ }
33
+ },
34
+ "required": []
35
+ }
@@ -0,0 +1,2 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export default function (tree: Tree): Promise<void>;
@@ -0,0 +1,41 @@
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
+ async function default_1(tree) {
6
+ const nxJson = (0, devkit_1.readNxJson)(tree);
7
+ const jestTargets = getJestTargetNames(tree);
8
+ const hasProductionFileset = !!nxJson.namedInputs?.production;
9
+ if (jestTargets.size > 0 && hasProductionFileset) {
10
+ const productionFileset = new Set(nxJson.namedInputs.production);
11
+ for (const exclusion of [
12
+ '!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)',
13
+ '!{projectRoot}/tsconfig.spec.json',
14
+ '!{projectRoot}/jest.config.[jt]s',
15
+ ]) {
16
+ productionFileset.add(exclusion);
17
+ }
18
+ nxJson.namedInputs.production = Array.from(productionFileset);
19
+ }
20
+ for (const targetName of jestTargets) {
21
+ nxJson.targetDefaults ??= {};
22
+ const jestTargetDefaults = (nxJson.targetDefaults[targetName] ??= {});
23
+ jestTargetDefaults.inputs ??= [
24
+ 'default',
25
+ hasProductionFileset ? '^production' : '^default',
26
+ ...(tree.exists('jest.preset.js')
27
+ ? ['{workspaceRoot}/jest.preset.js']
28
+ : []),
29
+ ];
30
+ }
31
+ (0, devkit_1.updateNxJson)(tree, nxJson);
32
+ await (0, devkit_1.formatFiles)(tree);
33
+ }
34
+ exports.default = default_1;
35
+ function getJestTargetNames(tree) {
36
+ const jestTargetNames = new Set();
37
+ (0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nrwl/jest:jest', (_, __, target) => {
38
+ jestTargetNames.add(target);
39
+ });
40
+ return jestTargetNames;
41
+ }
@@ -0,0 +1,3 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export declare function updateConfigsJest29(tree: Tree): Promise<void>;
3
+ export default updateConfigsJest29;