ts-jest 29.1.5 → 29.2.0

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.
package/.ts-jest-digest CHANGED
@@ -1 +1 @@
1
- fe39dee3cf86e90246fb615ac0e030c5cd17b1ee
1
+ 6514d17e165dc726d2f9e97b857c0b01ce3b4200
package/CHANGELOG.md CHANGED
@@ -1,3 +1,34 @@
1
+ ## 29.2.0 (2024-07-08)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * fix: don't show warning message with Node16/NodeNext ([99c4f49](https://github.com/kulshekhar/ts-jest/commit/99c4f49)), closes [#4266](https://github.com/kulshekhar/ts-jest/issues/4266)
7
+
8
+
9
+ ### Features
10
+
11
+ * feat(cli): allow migrating cjs `presets` to `transform` config ([22fb027](https://github.com/kulshekhar/ts-jest/commit/22fb027))
12
+ * feat(presets): add util functions to create ESM presets ([06f78ed](https://github.com/kulshekhar/ts-jest/commit/06f78ed))
13
+ * feat(presets): add util functions to create CJS presets ([f9cc3c0](https://github.com/kulshekhar/ts-jest/commit/f9cc3c0))
14
+
15
+
16
+ ### Code refactoring
17
+
18
+ * refactor: replace lodash deps with native js implementation ([40f1708](https://github.com/kulshekhar/ts-jest/commit/40f1708))
19
+ * refactor: use `TsJestTransformerOptions` type everywhere possibly ([7d001be](https://github.com/kulshekhar/ts-jest/commit/7d001be))
20
+ * refactor(cli): use new preset util functions to initialize test config ([c2b56ca](https://github.com/kulshekhar/ts-jest/commit/c2b56ca))
21
+ * refactor(presets): use create preset util functions for cjs presets ([922d6d0](https://github.com/kulshekhar/ts-jest/commit/922d6d0))
22
+ * test: switch `react-app` to use Vite ([827c8ad](https://github.com/kulshekhar/ts-jest/commit/827c8ad))
23
+
24
+
25
+ ## DEPRECATIONS
26
+
27
+ * refactor(cli): deprecate cli option `babel` ([9617029](https://github.com/kulshekhar/ts-jest/commit/9617029)). Please use CLI argument `--js babel` instead.
28
+ * `createJestPreset` is deprecated. Please check documentation at https://kulshekhar.github.io/ts-jest/docs/getting-started/presets to see alternative solutions.
29
+
30
+
31
+
1
32
  ## [29.1.5](https://github.com/kulshekhar/ts-jest/compare/v29.1.4...v29.1.5) (2024-06-16)
2
33
 
3
34
 
@@ -67,119 +67,83 @@ var __read = (this && this.__read) || function (o, n) {
67
67
  }
68
68
  return ar;
69
69
  };
70
+ var __importDefault = (this && this.__importDefault) || function (mod) {
71
+ return (mod && mod.__esModule) ? mod : { "default": mod };
72
+ };
70
73
  Object.defineProperty(exports, "__esModule", { value: true });
71
74
  exports.help = exports.run = void 0;
72
75
  var fs_1 = require("fs");
73
76
  var path_1 = require("path");
77
+ var ejs_1 = __importDefault(require("ejs"));
74
78
  var json5_1 = require("json5");
75
- var presets_1 = require("../helpers/presets");
79
+ var constants_1 = require("../../constants");
80
+ var create_jest_preset_1 = require("../../presets/create-jest-preset");
81
+ var ensureOnlyUsingDoubleQuotes = function (str) {
82
+ return str
83
+ .replace(/"'(.*?)'"/g, '"$1"')
84
+ .replace(/'ts-jest'/g, '"ts-jest"')
85
+ .replace(/'babel-jest'/g, '"babel-jest"');
86
+ };
76
87
  /**
77
88
  * @internal
78
89
  */
79
90
  var run = function (args /* , logger: Logger */) { return __awaiter(void 0, void 0, void 0, function () {
80
- var file, filePath, name, isPackage, exists, pkgFile, hasPackage, _a, jestPreset, askedTsconfig, force, jsdom, tsconfig, pkgJson, jsFilesProcessor, shouldPostProcessWithBabel, preset, body, jestConfig, transformerConfig, content, usesModules;
81
- var _b, _c, _d;
82
- return __generator(this, function (_e) {
91
+ var askedTsconfig, force, jsdom, jsFilesProcessor, shouldPostProcessWithBabel, file, filePath, name, isPackageJsonConfig, isJestConfigFileExisted, pkgFile, isPackageJsonExisted, tsconfig, pkgJsonContent, body, resolvedTsconfigOption, transformConfig, _a, transformPattern, transformValue;
92
+ var _b, _c;
93
+ return __generator(this, function (_d) {
94
+ askedTsconfig = args.tsconfig, force = args.force, jsdom = args.jsdom, jsFilesProcessor = args.js, shouldPostProcessWithBabel = args.babel;
83
95
  file = (_c = (_b = args._[0]) === null || _b === void 0 ? void 0 : _b.toString()) !== null && _c !== void 0 ? _c : 'jest.config.js';
84
96
  filePath = (0, path_1.join)(process.cwd(), file);
85
97
  name = (0, path_1.basename)(file);
86
- isPackage = name === 'package.json';
87
- exists = (0, fs_1.existsSync)(filePath);
88
- pkgFile = isPackage ? filePath : (0, path_1.join)(process.cwd(), 'package.json');
89
- hasPackage = isPackage || (0, fs_1.existsSync)(pkgFile);
90
- _a = args.jestPreset, jestPreset = _a === void 0 ? true : _a, askedTsconfig = args.tsconfig, force = args.force, jsdom = args.jsdom;
98
+ isPackageJsonConfig = name === 'package.json';
99
+ isJestConfigFileExisted = (0, fs_1.existsSync)(filePath);
100
+ pkgFile = isPackageJsonConfig ? filePath : (0, path_1.join)(process.cwd(), 'package.json');
101
+ isPackageJsonExisted = isPackageJsonConfig || (0, fs_1.existsSync)(pkgFile);
91
102
  tsconfig = askedTsconfig === 'tsconfig.json' ? undefined : askedTsconfig;
92
- pkgJson = hasPackage ? JSON.parse((0, fs_1.readFileSync)(pkgFile, 'utf8')) : {};
93
- jsFilesProcessor = args.js, shouldPostProcessWithBabel = args.babel;
94
- // set defaults for missing options
95
- if (jsFilesProcessor == null) {
96
- // set default js files processor depending on whether the user wants to post-process with babel
97
- jsFilesProcessor = shouldPostProcessWithBabel ? 'babel' : undefined;
98
- }
99
- else if (shouldPostProcessWithBabel == null) {
100
- // auto enables babel post-processing if the user wants babel to process js files
101
- shouldPostProcessWithBabel = jsFilesProcessor === 'babel';
103
+ pkgJsonContent = isPackageJsonExisted ? JSON.parse((0, fs_1.readFileSync)(pkgFile, 'utf8')) : {};
104
+ if (shouldPostProcessWithBabel) {
105
+ console.warn("The option --babel is deprecated and will be removed in the next major version." +
106
+ " Please specify 'js' option value (see more with npx ts-jest help) if you wish 'ts-jest' to process 'js' with TypeScript API or Babel.");
102
107
  }
103
- if (jsFilesProcessor === 'babel') {
104
- preset = presets_1.jsWIthBabel;
105
- }
106
- else if (jsFilesProcessor === 'ts') {
107
- preset = presets_1.jsWithTs;
108
- }
109
- else {
110
- preset = presets_1.defaults;
111
- }
112
- if (isPackage && !exists) {
108
+ if (isPackageJsonConfig && !isJestConfigFileExisted) {
113
109
  throw new Error("File ".concat(file, " does not exists."));
114
110
  }
115
- else if (!isPackage && exists && !force) {
111
+ else if (!isPackageJsonConfig && isJestConfigFileExisted && !force) {
116
112
  throw new Error("Configuration file ".concat(file, " already exists."));
117
113
  }
118
- if (!isPackage && !name.endsWith('.js')) {
114
+ if (!isPackageJsonConfig && !name.endsWith('.js')) {
119
115
  throw new TypeError("Configuration file ".concat(file, " must be a .js file or the package.json."));
120
116
  }
121
- if (hasPackage && pkgJson.jest) {
122
- if (force && !isPackage) {
123
- delete pkgJson.jest;
124
- (0, fs_1.writeFileSync)(pkgFile, JSON.stringify(pkgJson, undefined, ' '));
117
+ if (isPackageJsonExisted && pkgJsonContent.jest) {
118
+ if (force && !isPackageJsonConfig) {
119
+ delete pkgJsonContent.jest;
120
+ (0, fs_1.writeFileSync)(pkgFile, JSON.stringify(pkgJsonContent, undefined, ' '));
125
121
  }
126
122
  else if (!force) {
127
123
  throw new Error("A Jest configuration is already set in ".concat(pkgFile, "."));
128
124
  }
129
125
  }
130
- if (isPackage) {
131
- jestConfig = jestPreset ? { preset: preset.name } : __assign({}, preset.value);
132
- if (!jsdom)
133
- jestConfig.testEnvironment = 'node';
134
- transformerConfig = Object.entries((_d = jestConfig.transform) !== null && _d !== void 0 ? _d : {}).reduce(function (acc, _a) {
135
- var _b, _c;
136
- var _d = __read(_a, 2), fileRegex = _d[0], transformerConfig = _d[1];
137
- if (tsconfig || shouldPostProcessWithBabel) {
138
- var tsJestConf = {};
139
- if (tsconfig)
140
- tsJestConf.tsconfig = tsconfig;
141
- if (shouldPostProcessWithBabel)
142
- tsJestConf.babelConfig = true;
143
- return __assign(__assign({}, acc), (_b = {}, _b[fileRegex] = typeof transformerConfig === 'string'
144
- ? [transformerConfig, tsJestConf]
145
- : [transformerConfig[0], __assign(__assign({}, transformerConfig[1]), tsJestConf)], _b));
146
- }
147
- return __assign(__assign({}, acc), (_c = {}, _c[fileRegex] = transformerConfig, _c));
148
- }, {});
149
- if (Object.keys(transformerConfig).length) {
150
- jestConfig.transform = __assign(__assign({}, jestConfig.transform), transformerConfig);
151
- }
152
- body = JSON.stringify(__assign(__assign({}, pkgJson), { jest: jestConfig }), undefined, ' ');
126
+ resolvedTsconfigOption = tsconfig ? { tsconfig: "".concat((0, json5_1.stringify)(tsconfig)) } : undefined;
127
+ if (jsFilesProcessor === 'babel' || shouldPostProcessWithBabel) {
128
+ transformConfig = (0, create_jest_preset_1.createJsWithBabelPreset)(resolvedTsconfigOption);
129
+ }
130
+ else if (jsFilesProcessor === 'ts') {
131
+ transformConfig = (0, create_jest_preset_1.createJsWithTsPreset)(resolvedTsconfigOption);
153
132
  }
154
133
  else {
155
- content = [];
156
- if (!jestPreset) {
157
- content.push("".concat(preset.jsImport('tsjPreset'), ";"), '');
158
- }
159
- content.push("/** @type {import('ts-jest').JestConfigWithTsJest} */");
160
- usesModules = pkgJson.type === 'module';
161
- content.push(usesModules ? 'export default {' : 'module.exports = {');
162
- if (jestPreset) {
163
- content.push(" preset: '".concat(preset.name, "',"));
164
- }
165
- else {
166
- content.push(' ...tsjPreset,');
167
- }
168
- if (!jsdom)
169
- content.push(" testEnvironment: 'node',");
170
- if (tsconfig || shouldPostProcessWithBabel) {
171
- content.push(' transform: {');
172
- content.push(" '^.+\\\\.[tj]sx?$': ['ts-jest', {");
173
- if (tsconfig)
174
- content.push(" tsconfig: ".concat((0, json5_1.stringify)(tsconfig), ","));
175
- if (shouldPostProcessWithBabel)
176
- content.push(' babelConfig: true,');
177
- content.push(' }],');
178
- content.push(' },');
179
- }
180
- content.push('};');
181
- // join all together
182
- body = content.join('\n');
134
+ transformConfig = (0, create_jest_preset_1.createDefaultPreset)(resolvedTsconfigOption);
135
+ }
136
+ if (isPackageJsonConfig) {
137
+ body = ensureOnlyUsingDoubleQuotes(JSON.stringify(__assign(__assign({}, pkgJsonContent), { jest: transformConfig }), undefined, ' '));
138
+ }
139
+ else {
140
+ _a = __read(Object.entries(transformConfig.transform)[0], 2), transformPattern = _a[0], transformValue = _a[1];
141
+ body = ejs_1.default.render(constants_1.JEST_CONFIG_EJS_TEMPLATE, {
142
+ exportKind: pkgJsonContent.type === 'module' ? 'export default' : 'module.exports =',
143
+ testEnvironment: jsdom ? 'jsdom' : 'node',
144
+ transformPattern: transformPattern,
145
+ transformValue: ensureOnlyUsingDoubleQuotes((0, json5_1.stringify)(transformValue)),
146
+ });
183
147
  }
184
148
  (0, fs_1.writeFileSync)(filePath, body);
185
149
  process.stderr.write("\nJest configuration written to \"".concat(filePath, "\".\n"));
@@ -192,7 +156,7 @@ exports.run = run;
192
156
  */
193
157
  var help = function () { return __awaiter(void 0, void 0, void 0, function () {
194
158
  return __generator(this, function (_a) {
195
- process.stdout.write("\nUsage:\n ts-jest config:init [options] [<config-file>]\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n Default: jest.config.js\n\nOptions:\n --force Discard any existing Jest config\n --js ts|babel Process .js files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n --tsconfig <file> Path to the tsconfig.json file\n --babel Pipe babel-jest after ts-jest\n --jsdom Use jsdom as test environment instead of node\n");
159
+ process.stdout.write("\nUsage:\n ts-jest config:init [options] [<config-file>]\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n Default: jest.config.js\n\nOptions:\n --force Discard any existing Jest config\n --js ts|babel Process '.js' files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n --tsconfig <file> Path to the tsconfig.json file\n --babel Enable using Babel to process 'js' resulted content from 'ts-jest' processing\n --jsdom Use 'jsdom' as test environment instead of 'node'\n");
196
160
  return [2 /*return*/];
197
161
  });
198
162
  }); };
@@ -62,15 +62,6 @@ var __read = (this && this.__read) || function (o, n) {
62
62
  }
63
63
  return ar;
64
64
  };
65
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
66
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
67
- if (ar || !(i in from)) {
68
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
69
- ar[i] = from[i];
70
- }
71
- }
72
- return to.concat(ar || Array.prototype.slice.call(from));
73
- };
74
65
  var __importDefault = (this && this.__importDefault) || function (mod) {
75
66
  return (mod && mod.__esModule) ? mod : { "default": mod };
76
67
  };
@@ -81,19 +72,43 @@ var path_1 = require("path");
81
72
  var bs_logger_1 = require("bs-logger");
82
73
  var fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify"));
83
74
  var json5_1 = require("json5");
75
+ var create_jest_preset_1 = require("../../presets/create-jest-preset");
84
76
  var backports_1 = require("../../utils/backports");
85
77
  var presets_1 = require("../helpers/presets");
78
+ var migrateGlobalConfigToTransformConfig = function (transformConfig, globalsTsJestConfig) {
79
+ if (transformConfig) {
80
+ return Object.entries(transformConfig).reduce(function (previousValue, currentValue) {
81
+ var _a, _b;
82
+ var _c = __read(currentValue, 2), key = _c[0], transformOptions = _c[1];
83
+ if (typeof transformOptions === 'string' && transformOptions.includes('ts-jest')) {
84
+ return __assign(__assign({}, previousValue), (_a = {}, _a[key] = globalsTsJestConfig ? ['ts-jest', globalsTsJestConfig] : 'ts-jest', _a));
85
+ }
86
+ return __assign(__assign({}, previousValue), (_b = {}, _b[key] = transformOptions, _b));
87
+ }, {});
88
+ }
89
+ return {};
90
+ };
91
+ var migratePresetToTransformConfig = function (transformConfig, preset, globalsTsJestConfig) {
92
+ if (preset) {
93
+ var transformConfigFromPreset = preset.name === "ts-jest/presets/js-with-ts" /* JestPresetNames.jsWithTs */
94
+ ? (0, create_jest_preset_1.createJsWithTsPreset)(globalsTsJestConfig)
95
+ : preset.name === "ts-jest/presets/js-with-babel" /* JestPresetNames.jsWIthBabel */
96
+ ? (0, create_jest_preset_1.createJsWithBabelPreset)(globalsTsJestConfig)
97
+ : (0, create_jest_preset_1.createDefaultPreset)(globalsTsJestConfig);
98
+ return __assign(__assign({}, transformConfig), transformConfigFromPreset.transform);
99
+ }
100
+ return transformConfig;
101
+ };
86
102
  /**
87
103
  * @internal
88
104
  */
89
105
  var run = function (args /* , logger: Logger*/) { return __awaiter(void 0, void 0, void 0, function () {
90
- var nullLogger, file, filePath, footNotes, name, isPackage, actualConfig, migratedConfig, presetName, preset, jsTransformers, jsWithTs, jsWithBabel, presetValue, migratedValue, presetValue, migratedValue, globalsTsJestConfig, migratedConfigTransform, presetValueTransform_1, before, after, stringify, prefix;
91
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
92
- return __generator(this, function (_l) {
106
+ var nullLogger, file, filePath, name, isPackage, actualConfig, migratedConfig, preset, presetValue, migratedValue, presetValue, migratedValue, globalsTsJestConfig, before, after, stringify, prefix;
107
+ var _a, _b, _c, _d, _e, _f, _g, _h;
108
+ return __generator(this, function (_j) {
93
109
  nullLogger = (0, bs_logger_1.createLogger)({ targets: [] });
94
110
  file = (_a = args._[0]) === null || _a === void 0 ? void 0 : _a.toString();
95
111
  filePath = (0, path_1.resolve)(process.cwd(), file);
96
- footNotes = [];
97
112
  if (!(0, fs_1.existsSync)(filePath)) {
98
113
  throw new Error("Configuration file ".concat(file, " does not exists."));
99
114
  }
@@ -110,129 +125,41 @@ var run = function (args /* , logger: Logger*/) { return __awaiter(void 0, void
110
125
  if (!actualConfig)
111
126
  actualConfig = {};
112
127
  migratedConfig = (0, backports_1.backportJestConfig)(nullLogger, actualConfig);
113
- // then we check if we can use `preset`
114
- if (!migratedConfig.preset && args.jestPreset) {
115
- // find the best preset
116
- if (args.js) {
117
- presetName = args.js === 'babel' ? "ts-jest/presets/js-with-babel" /* JestPresetNames.jsWIthBabel */ : "ts-jest/presets/js-with-ts" /* JestPresetNames.jsWithTs */;
118
- }
119
- else {
120
- jsTransformers = Object.keys(migratedConfig.transform || {}).reduce(function (list, pattern) {
121
- if (RegExp(pattern.replace(/^<rootDir>\/?/, '/dummy-project/')).test('/dummy-project/src/foo.js')) {
122
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
123
- var transformer = migratedConfig.transform[pattern];
124
- if (/\bbabel-jest\b/.test(transformer))
125
- transformer = 'babel-jest';
126
- else if (/\ts-jest\b/.test(transformer))
127
- transformer = 'ts-jest';
128
- return __spreadArray(__spreadArray([], __read(list), false), [transformer], false);
129
- }
130
- return list;
131
- }, []);
132
- jsWithTs = jsTransformers.includes('ts-jest');
133
- jsWithBabel = jsTransformers.includes('babel-jest');
134
- if (jsWithBabel && !jsWithTs) {
135
- presetName = "ts-jest/presets/js-with-babel" /* JestPresetNames.jsWIthBabel */;
136
- }
137
- else if (jsWithTs && !jsWithBabel) {
138
- presetName = "ts-jest/presets/js-with-ts" /* JestPresetNames.jsWithTs */;
139
- }
140
- else {
141
- // sounds like js files are NOT handled, or handled with a unknown transformer, so we do not need to handle it
142
- presetName = "ts-jest/presets/default" /* JestPresetNames.default */;
143
- }
144
- }
145
- // ensure we are using a preset
146
- presetName = presetName !== null && presetName !== void 0 ? presetName : "ts-jest/presets/default" /* JestPresetNames.default */;
147
- preset = presets_1.allPresets[presetName];
148
- footNotes.push("Detected preset '".concat(preset.label, "' as the best matching preset for your configuration.\nVisit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more information about presets.\n"));
128
+ if (migratedConfig.preset) {
129
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
130
+ preset = (_b = presets_1.allPresets[migratedConfig.preset]) !== null && _b !== void 0 ? _b : presets_1.allPresets["ts-jest/presets/default" /* JestPresetNames.default */];
149
131
  }
150
- else if ((_b = migratedConfig.preset) === null || _b === void 0 ? void 0 : _b.startsWith('ts-jest')) {
151
- if (args.jestPreset === false) {
152
- delete migratedConfig.preset;
132
+ else {
133
+ if (args.js) {
134
+ preset = args.js === 'babel' ? presets_1.allPresets["ts-jest/presets/js-with-babel" /* JestPresetNames.jsWIthBabel */] : presets_1.allPresets["ts-jest/presets/js-with-ts" /* JestPresetNames.jsWithTs */];
153
135
  }
154
136
  else {
155
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
156
- preset = (_c = presets_1.allPresets[migratedConfig.preset]) !== null && _c !== void 0 ? _c : presets_1.defaults;
137
+ preset = presets_1.allPresets["ts-jest/presets/default" /* JestPresetNames.default */];
157
138
  }
158
139
  }
159
- // enforce the correct name
160
- if (preset)
161
- migratedConfig.preset = preset.name;
162
140
  // check the extensions
163
- if (((_d = migratedConfig.moduleFileExtensions) === null || _d === void 0 ? void 0 : _d.length) && preset) {
164
- presetValue = dedupSort((_e = preset.value.moduleFileExtensions) !== null && _e !== void 0 ? _e : []).join('::');
141
+ if (((_c = migratedConfig.moduleFileExtensions) === null || _c === void 0 ? void 0 : _c.length) && preset) {
142
+ presetValue = dedupSort((_d = preset.value.moduleFileExtensions) !== null && _d !== void 0 ? _d : []).join('::');
165
143
  migratedValue = dedupSort(migratedConfig.moduleFileExtensions).join('::');
166
144
  if (presetValue === migratedValue) {
167
145
  delete migratedConfig.moduleFileExtensions;
168
146
  }
169
147
  }
170
148
  // there is a testRegex, remove our testMatch
171
- if ((typeof migratedConfig.testRegex === 'string' || ((_f = migratedConfig.testRegex) === null || _f === void 0 ? void 0 : _f.length)) && preset) {
149
+ if (typeof migratedConfig.testRegex === 'string' || ((_e = migratedConfig.testRegex) === null || _e === void 0 ? void 0 : _e.length)) {
172
150
  delete migratedConfig.testMatch;
173
151
  }
174
152
  // check the testMatch
175
- else if (((_g = migratedConfig.testMatch) === null || _g === void 0 ? void 0 : _g.length) && preset) {
176
- presetValue = dedupSort((_h = preset.value.testMatch) !== null && _h !== void 0 ? _h : []).join('::');
153
+ else if (((_f = migratedConfig.testMatch) === null || _f === void 0 ? void 0 : _f.length) && preset) {
154
+ presetValue = dedupSort((_g = preset.value.testMatch) !== null && _g !== void 0 ? _g : []).join('::');
177
155
  migratedValue = dedupSort(migratedConfig.testMatch).join('::');
178
156
  if (presetValue === migratedValue) {
179
157
  delete migratedConfig.testMatch;
180
158
  }
181
159
  }
182
- // migrate the transform
183
- if (migratedConfig.transform) {
184
- Object.keys(migratedConfig.transform).forEach(function (key) {
185
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
186
- var val = migratedConfig.transform[key];
187
- if (typeof val === 'string' && /\/?ts-jest?(?:\/preprocessor\.js)?$/.test(val)) {
188
- // eslint-disable-next-line
189
- ;
190
- migratedConfig.transform[key] = 'ts-jest';
191
- }
192
- });
193
- }
194
- globalsTsJestConfig = (_j = migratedConfig.globals) === null || _j === void 0 ? void 0 : _j['ts-jest'];
195
- if (globalsTsJestConfig && migratedConfig.transform) {
196
- Object.keys(migratedConfig.transform).forEach(function (key) {
197
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
198
- var val = migratedConfig.transform[key];
199
- if (typeof val === 'string' && val.includes('ts-jest')) {
200
- // eslint-disable-next-line
201
- ;
202
- migratedConfig.transform[key] = Object.keys(globalsTsJestConfig).length ? [val, globalsTsJestConfig] : val;
203
- }
204
- });
205
- delete ((_k = migratedConfig.globals) !== null && _k !== void 0 ? _k : Object.create(null))['ts-jest'];
206
- }
207
- // check if it's the same as the preset's one
208
- if (preset && migratedConfig.transform) {
209
- if ((0, fast_json_stable_stringify_1.default)(migratedConfig.transform) === (0, fast_json_stable_stringify_1.default)(preset.value.transform)) {
210
- delete migratedConfig.transform;
211
- }
212
- else {
213
- migratedConfigTransform = migratedConfig.transform;
214
- presetValueTransform_1 = preset.value.transform;
215
- if (migratedConfigTransform && presetValueTransform_1) {
216
- migratedConfig.transform = Object.entries(migratedConfigTransform).reduce(
217
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
218
- function (acc, _a) {
219
- var _b, _c;
220
- var _d = __read(_a, 2), fileRegex = _d[0], transformerConfig = _d[1];
221
- var presetValueTransformerConfig = presetValueTransform_1[fileRegex];
222
- var shouldRemoveDuplicatedConfig = (presetValueTransformerConfig &&
223
- Array.isArray(presetValueTransformerConfig) &&
224
- transformerConfig === presetValueTransformerConfig[0] &&
225
- !Object.keys(presetValueTransformerConfig[1]).length) ||
226
- transformerConfig === presetValueTransformerConfig;
227
- return shouldRemoveDuplicatedConfig
228
- ? acc
229
- : acc
230
- ? __assign(__assign({}, acc), (_b = {}, _b[fileRegex] = transformerConfig, _b)) : (_c = {}, _c[fileRegex] = transformerConfig, _c);
231
- }, undefined);
232
- }
233
- }
234
- }
235
- // cleanup
160
+ globalsTsJestConfig = (_h = migratedConfig.globals) === null || _h === void 0 ? void 0 : _h['ts-jest'];
161
+ migratedConfig.transform = migrateGlobalConfigToTransformConfig(migratedConfig.transform, globalsTsJestConfig);
162
+ migratedConfig.transform = migratePresetToTransformConfig(migratedConfig.transform, preset, globalsTsJestConfig);
236
163
  cleanupConfig(actualConfig);
237
164
  cleanupConfig(migratedConfig);
238
165
  before = (0, fast_json_stable_stringify_1.default)(actualConfig);
@@ -243,38 +170,16 @@ var run = function (args /* , logger: Logger*/) { return __awaiter(void 0, void
243
170
  }
244
171
  stringify = file.endsWith('.json') ? JSON.stringify : json5_1.stringify;
245
172
  prefix = file.endsWith('.json') ? '"jest": ' : 'module.exports = ';
246
- // if we are using preset, inform the user that he might be able to remove some section(s)
247
- // we couldn't check for equality
248
- // if (usesPreset && migratedConfig.testMatch) {
249
- // footNotes.push(`
250
- // I couldn't check if your "testMatch" value is the same as mine which is: ${stringify(
251
- // presets.testMatch,
252
- // undefined,
253
- // ' ',
254
- // )}
255
- // If it is the case, you can safely remove the "testMatch" from what I've migrated.
256
- // `)
257
- // }
258
- if (preset && migratedConfig.transform) {
259
- footNotes.push("\nI couldn't check if your \"transform\" value is the same as mine which is: ".concat(stringify(preset.value.transform, undefined, ' '), "\nIf it is the case, you can safely remove the \"transform\" from what I've migrated.\n"));
260
- }
261
173
  // output new config
262
174
  process.stderr.write("\nMigrated Jest configuration:\n");
263
175
  process.stdout.write("".concat(prefix).concat(stringify(migratedConfig, undefined, ' '), "\n"));
264
- if (footNotes.length) {
265
- process.stderr.write("\n".concat(footNotes.join('\n'), "\n"));
266
- }
267
176
  return [2 /*return*/];
268
177
  });
269
178
  }); };
270
179
  exports.run = run;
271
180
  function cleanupConfig(config) {
272
181
  if (config.globals) {
273
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
274
- if (config.globals['ts-jest'] && Object.keys(config.globals['ts-jest']).length === 0) {
275
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
276
- delete config.globals['ts-jest'];
277
- }
182
+ delete config.globals['ts-jest'];
278
183
  if (!Object.keys(config.globals).length) {
279
184
  delete config.globals;
280
185
  }
@@ -292,8 +197,7 @@ function cleanupConfig(config) {
292
197
  if (!config.testMatch.length)
293
198
  delete config.testMatch;
294
199
  }
295
- if (config.preset === "ts-jest/presets/default" /* JestPresetNames.default */)
296
- config.preset = presets_1.defaults.name;
200
+ delete config.preset;
297
201
  }
298
202
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
299
203
  function dedupSort(arr) {
package/dist/cli/index.js CHANGED
@@ -40,7 +40,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
40
40
  };
41
41
  var _a;
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
- exports.processArgv = void 0;
43
+ exports.processArgv = processArgv;
44
44
  var bs_logger_1 = require("bs-logger");
45
45
  var yargs_parser_1 = __importDefault(require("yargs-parser"));
46
46
  var utils_1 = require("../utils");
@@ -115,4 +115,3 @@ function processArgv() {
115
115
  });
116
116
  });
117
117
  }
118
- exports.processArgv = processArgv;
@@ -1,7 +1,9 @@
1
1
  import type { Config } from '@jest/types';
2
+ import type { CompilerOptions } from 'typescript';
3
+ type TsPathMapping = Exclude<CompilerOptions['paths'], undefined>;
2
4
  type JestPathMapping = Config.InitialOptions['moduleNameMapper'];
3
- export declare const pathsToModuleNameMapper: (mapping: import("typescript").MapLike<string[]>, { prefix, useESM }?: {
4
- prefix?: string | undefined;
5
- useESM?: boolean | undefined;
5
+ export declare const pathsToModuleNameMapper: (mapping: TsPathMapping, { prefix, useESM }?: {
6
+ prefix?: string;
7
+ useESM?: boolean;
6
8
  }) => JestPathMapping;
7
9
  export {};
@@ -3,5 +3,11 @@ export declare const DECLARATION_TYPE_EXT = ".d.ts";
3
3
  export declare const JS_JSX_EXTENSIONS: string[];
4
4
  export declare const TS_TSX_REGEX: RegExp;
5
5
  export declare const JS_JSX_REGEX: RegExp;
6
+ export declare const TS_TRANSFORM_PATTERN = "^.+.tsx?$";
7
+ export declare const ESM_TS_TRANSFORM_PATTERN = "^.+\\.m?tsx?$";
8
+ export declare const TS_JS_TRANSFORM_PATTERN = "^.+.[tj]sx?$";
9
+ export declare const ESM_TS_JS_TRANSFORM_PATTERN = "^.+\\.m?[tj]sx?$";
10
+ export declare const JS_TRANSFORM_PATTERN = "^.+.jsx?$";
11
+ export declare const ESM_JS_TRANSFORM_PATTERN = "^.+\\.m?jsx?$";
6
12
  export declare const TS_EXT_TO_TREAT_AS_ESM: string[];
7
13
  export declare const JS_EXT_TO_TREAT_AS_ESM: string[];
package/dist/constants.js CHANGED
@@ -1,11 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEFAULT_JEST_TEST_MATCH = exports.JS_EXT_TO_TREAT_AS_ESM = exports.TS_EXT_TO_TREAT_AS_ESM = exports.JS_JSX_REGEX = exports.TS_TSX_REGEX = exports.JS_JSX_EXTENSIONS = exports.DECLARATION_TYPE_EXT = exports.LINE_FEED = void 0;
3
+ exports.JEST_CONFIG_EJS_TEMPLATE = exports.DEFAULT_JEST_TEST_MATCH = exports.JS_EXT_TO_TREAT_AS_ESM = exports.TS_EXT_TO_TREAT_AS_ESM = exports.ESM_JS_TRANSFORM_PATTERN = exports.JS_TRANSFORM_PATTERN = exports.ESM_TS_JS_TRANSFORM_PATTERN = exports.TS_JS_TRANSFORM_PATTERN = exports.ESM_TS_TRANSFORM_PATTERN = exports.TS_TRANSFORM_PATTERN = exports.JS_JSX_REGEX = exports.TS_TSX_REGEX = exports.JS_JSX_EXTENSIONS = exports.DECLARATION_TYPE_EXT = exports.LINE_FEED = void 0;
4
4
  exports.LINE_FEED = '\n';
5
5
  exports.DECLARATION_TYPE_EXT = '.d.ts';
6
6
  exports.JS_JSX_EXTENSIONS = ['.js', '.jsx'];
7
7
  exports.TS_TSX_REGEX = /\.[cm]?tsx?$/;
8
8
  exports.JS_JSX_REGEX = /\.[cm]?jsx?$/;
9
+ exports.TS_TRANSFORM_PATTERN = '^.+.tsx?$';
10
+ exports.ESM_TS_TRANSFORM_PATTERN = '^.+\\.m?tsx?$';
11
+ exports.TS_JS_TRANSFORM_PATTERN = '^.+.[tj]sx?$';
12
+ exports.ESM_TS_JS_TRANSFORM_PATTERN = '^.+\\.m?[tj]sx?$';
13
+ exports.JS_TRANSFORM_PATTERN = '^.+.jsx?$';
14
+ exports.ESM_JS_TRANSFORM_PATTERN = '^.+\\.m?jsx?$';
9
15
  // `extensionsToTreatAsEsm` will throw error with `.mjs`
10
16
  exports.TS_EXT_TO_TREAT_AS_ESM = ['.ts', '.tsx', '.mts'];
11
17
  exports.JS_EXT_TO_TREAT_AS_ESM = ['.jsx'];
@@ -14,3 +20,7 @@ exports.JS_EXT_TO_TREAT_AS_ESM = ['.jsx'];
14
20
  * See https://jestjs.io/docs/en/configuration#testmatch-arraystring
15
21
  */
16
22
  exports.DEFAULT_JEST_TEST_MATCH = ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'];
23
+ /**
24
+ * @internal
25
+ */
26
+ exports.JEST_CONFIG_EJS_TEMPLATE = "/** @type {import('ts-jest').JestConfigWithTsJest} **/\n<%= exportKind %> {\n testEnvironment: \"<%= testEnvironment %>\",\n transform: {\n \"<%= transformPattern %>\": <%- transformValue %>,\n },\n};";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TsJestTransformer } from './legacy/ts-jest-transformer';
2
- import type { TsJestGlobalOptions } from './types';
2
+ import type { TsJestTransformerOptions } from './types';
3
3
  export * from './config';
4
4
  export * from './constants';
5
5
  export * from './legacy/compiler';
@@ -10,6 +10,6 @@ export * from './raw-compiler-options';
10
10
  export * from './utils';
11
11
  export * from './types';
12
12
  declare const _default: {
13
- createTransformer(tsJestConfig?: TsJestGlobalOptions): TsJestTransformer;
13
+ createTransformer(tsJestConfig?: TsJestTransformerOptions): TsJestTransformer;
14
14
  };
15
15
  export default _default;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.updateOutput = exports.SOURCE_MAPPING_PREFIX = void 0;
3
+ exports.SOURCE_MAPPING_PREFIX = void 0;
4
+ exports.updateOutput = updateOutput;
4
5
  var utils_1 = require("../../utils");
5
6
  /**
6
7
  * Rely on TypeScript compiled output generation which contains this prefix to point to sourcemap location.
@@ -19,7 +20,6 @@ function updateOutput(outputText, normalizedFileName, sourceMap) {
19
20
  }
20
21
  return outputText;
21
22
  }
22
- exports.updateOutput = updateOutput;
23
23
  /**
24
24
  * Update the source map contents for improved output.
25
25
  */
@@ -107,8 +107,8 @@ exports.MY_DIGEST = (0, fs_1.readFileSync)((0, path_1.resolve)(__dirname, '../..
107
107
  * @internal
108
108
  */
109
109
  exports.IGNORE_DIAGNOSTIC_CODES = [
110
- 6059,
111
- 18002,
110
+ 6059, // "'rootDir' is expected to contain all source files."
111
+ 18002, // "The 'files' list in config file is empty."
112
112
  18003, // "No inputs were found in config file."
113
113
  ];
114
114
  /**
@@ -184,13 +184,13 @@ var ConfigSet = /** @class */ (function () {
184
184
  inlineSourceMap: false,
185
185
  // we don't want to create declaration files
186
186
  declaration: false,
187
- noEmit: false,
187
+ noEmit: false, // set to true will make compiler API not emit any compiled results.
188
188
  // else istanbul related will be dropped
189
189
  removeComments: false,
190
190
  // to clear out else it's buggy
191
191
  out: undefined,
192
192
  outFile: undefined,
193
- composite: undefined,
193
+ composite: undefined, // see https://github.com/TypeStrong/ts-node/pull/657/files
194
194
  declarationDir: undefined,
195
195
  declarationMap: undefined,
196
196
  emitDeclarationOnly: undefined,
@@ -419,8 +419,13 @@ var ConfigSet = /** @class */ (function () {
419
419
  ? this.compilerModule.ModuleKind.CommonJS
420
420
  : this.compilerModule.ModuleKind.ESNext;
421
421
  var moduleValue = (_c = finalOptions.module) !== null && _c !== void 0 ? _c : defaultModule;
422
+ var warningModulesForEsmInterop = [
423
+ this.compilerModule.ModuleKind.CommonJS,
424
+ this.compilerModule.ModuleKind.Node16,
425
+ this.compilerModule.ModuleKind.NodeNext,
426
+ ];
422
427
  if (!this.babelConfig &&
423
- moduleValue !== this.compilerModule.ModuleKind.CommonJS &&
428
+ !warningModulesForEsmInterop.includes(moduleValue) &&
424
429
  !(finalOptions.esModuleInterop || finalOptions.allowSyntheticDefaultImports)) {
425
430
  result.errors.push({
426
431
  code: 151001 /* DiagnosticCodes.ConfigModuleOption */,
@@ -1,6 +1,6 @@
1
- import type { TsJestGlobalOptions } from '../types';
1
+ import type { TsJestTransformerOptions } from '../types';
2
2
  import { TsJestTransformer } from './ts-jest-transformer';
3
3
  declare const _default: {
4
- createTransformer: (tsJestConfig?: TsJestGlobalOptions) => TsJestTransformer;
4
+ createTransformer: (tsJestConfig?: TsJestTransformerOptions) => TsJestTransformer;
5
5
  };
6
6
  export default _default;