normalize.js
37.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = normalize;
function _crypto() {
const data = require('crypto');
_crypto = function () {
return data;
};
return data;
}
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _deepmerge() {
const data = _interopRequireDefault(require('deepmerge'));
_deepmerge = function () {
return data;
};
return data;
}
function _glob() {
const data = require('glob');
_glob = function () {
return data;
};
return data;
}
function _gracefulFs() {
const data = require('graceful-fs');
_gracefulFs = function () {
return data;
};
return data;
}
function _micromatch() {
const data = _interopRequireDefault(require('micromatch'));
_micromatch = function () {
return data;
};
return data;
}
function _jestRegexUtil() {
const data = require('jest-regex-util');
_jestRegexUtil = function () {
return data;
};
return data;
}
function _jestResolve() {
const data = _interopRequireWildcard(require('jest-resolve'));
_jestResolve = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _jestValidate() {
const data = require('jest-validate');
_jestValidate = function () {
return data;
};
return data;
}
var _Defaults = _interopRequireDefault(require('./Defaults'));
var _Deprecated = _interopRequireDefault(require('./Deprecated'));
var _ReporterValidationErrors = require('./ReporterValidationErrors');
var _ValidConfig = _interopRequireDefault(require('./ValidConfig'));
var _color = require('./color');
var _constants = require('./constants');
var _getMaxWorkers = _interopRequireDefault(require('./getMaxWorkers'));
var _setFromArgv = _interopRequireDefault(require('./setFromArgv'));
var _utils = require('./utils');
var _validatePattern = _interopRequireDefault(require('./validatePattern'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const ERROR = `${_utils.BULLET}Validation Error`;
const PRESET_EXTENSIONS = ['.json', '.js', '.cjs', '.mjs'];
const PRESET_NAME = 'jest-preset';
const createConfigError = message =>
new (_jestValidate().ValidationError)(
ERROR,
message,
_utils.DOCUMENTATION_NOTE
);
function verifyDirectoryExists(path, key) {
try {
const rootStat = (0, _gracefulFs().statSync)(path);
if (!rootStat.isDirectory()) {
throw createConfigError(
` ${_chalk().default.bold(path)} in the ${_chalk().default.bold(
key
)} option is not a directory.`
);
}
} catch (err) {
if (err instanceof _jestValidate().ValidationError) {
throw err;
}
if (err.code === 'ENOENT') {
throw createConfigError(
` Directory ${_chalk().default.bold(
path
)} in the ${_chalk().default.bold(key)} option was not found.`
);
} // Not sure in which cases `statSync` can throw, so let's just show the underlying error to the user
throw createConfigError(
` Got an error trying to find ${_chalk().default.bold(
path
)} in the ${_chalk().default.bold(key)} option.\n\n Error was: ${
err.message
}`
);
}
} // TS 3.5 forces us to split these into 2
const mergeModuleNameMapperWithPreset = (options, preset) => {
if (options['moduleNameMapper'] && preset['moduleNameMapper']) {
options['moduleNameMapper'] = {
...options['moduleNameMapper'],
...preset['moduleNameMapper'],
...options['moduleNameMapper']
};
}
};
const mergeTransformWithPreset = (options, preset) => {
if (options['transform'] && preset['transform']) {
options['transform'] = {
...options['transform'],
...preset['transform'],
...options['transform']
};
}
};
const mergeGlobalsWithPreset = (options, preset) => {
if (options['globals'] && preset['globals']) {
options['globals'] = (0, _deepmerge().default)(
preset['globals'],
options['globals']
);
}
};
const setupPreset = async (options, optionsPreset) => {
let preset;
const presetPath = (0, _utils.replaceRootDirInPath)(
options.rootDir,
optionsPreset
);
const presetModule = _jestResolve().default.findNodeModule(
presetPath.startsWith('.')
? presetPath
: path().join(presetPath, PRESET_NAME),
{
basedir: options.rootDir,
extensions: PRESET_EXTENSIONS
}
);
try {
if (!presetModule) {
throw new Error(`Cannot find module '${presetPath}'`);
} // Force re-evaluation to support multiple projects
try {
delete require.cache[require.resolve(presetModule)];
} catch {}
preset = await (0, _jestUtil().requireOrImportModule)(presetModule);
} catch (error) {
if (error instanceof SyntaxError || error instanceof TypeError) {
throw createConfigError(
` Preset ${_chalk().default.bold(presetPath)} is invalid:\n\n ${
error.message
}\n ${error.stack}`
);
}
if (error.message.includes('Cannot find module')) {
if (error.message.includes(presetPath)) {
const preset = _jestResolve().default.findNodeModule(presetPath, {
basedir: options.rootDir
});
if (preset) {
throw createConfigError(
` Module ${_chalk().default.bold(
presetPath
)} should have "jest-preset.js" or "jest-preset.json" file at the root.`
);
}
throw createConfigError(
` Preset ${_chalk().default.bold(presetPath)} not found.`
);
}
throw createConfigError(
` Missing dependency in ${_chalk().default.bold(presetPath)}:\n\n ${
error.message
}\n ${error.stack}`
);
}
throw createConfigError(
` An unknown error occurred in ${_chalk().default.bold(
presetPath
)}:\n\n ${error.message}\n ${error.stack}`
);
}
if (options.setupFiles) {
options.setupFiles = (preset.setupFiles || []).concat(options.setupFiles);
}
if (options.setupFilesAfterEnv) {
options.setupFilesAfterEnv = (preset.setupFilesAfterEnv || []).concat(
options.setupFilesAfterEnv
);
}
if (options.modulePathIgnorePatterns && preset.modulePathIgnorePatterns) {
options.modulePathIgnorePatterns = preset.modulePathIgnorePatterns.concat(
options.modulePathIgnorePatterns
);
}
mergeModuleNameMapperWithPreset(options, preset);
mergeTransformWithPreset(options, preset);
mergeGlobalsWithPreset(options, preset);
return {...preset, ...options};
};
const setupBabelJest = options => {
const transform = options.transform;
let babelJest;
if (transform) {
const customJSPattern = Object.keys(transform).find(pattern => {
const regex = new RegExp(pattern);
return regex.test('a.js') || regex.test('a.jsx');
});
const customTSPattern = Object.keys(transform).find(pattern => {
const regex = new RegExp(pattern);
return regex.test('a.ts') || regex.test('a.tsx');
});
[customJSPattern, customTSPattern].forEach(pattern => {
if (pattern) {
const customTransformer = transform[pattern];
if (Array.isArray(customTransformer)) {
if (customTransformer[0] === 'babel-jest') {
babelJest = require.resolve('babel-jest');
customTransformer[0] = babelJest;
} else if (customTransformer[0].includes('babel-jest')) {
babelJest = customTransformer[0];
}
} else {
if (customTransformer === 'babel-jest') {
babelJest = require.resolve('babel-jest');
transform[pattern] = babelJest;
} else if (customTransformer.includes('babel-jest')) {
babelJest = customTransformer;
}
}
}
});
} else {
babelJest = require.resolve('babel-jest');
options.transform = {
[_constants.DEFAULT_JS_PATTERN]: babelJest
};
}
};
const normalizeCollectCoverageOnlyFrom = (options, key) => {
const initialCollectCoverageFrom = options[key];
const collectCoverageOnlyFrom = Array.isArray(initialCollectCoverageFrom)
? initialCollectCoverageFrom // passed from argv
: Object.keys(initialCollectCoverageFrom); // passed from options
return collectCoverageOnlyFrom.reduce((map, filePath) => {
filePath = path().resolve(
options.rootDir,
(0, _utils.replaceRootDirInPath)(options.rootDir, filePath)
);
map[filePath] = true;
return map;
}, Object.create(null));
};
const normalizeCollectCoverageFrom = (options, key) => {
const initialCollectCoverageFrom = options[key];
let value;
if (!initialCollectCoverageFrom) {
value = [];
}
if (!Array.isArray(initialCollectCoverageFrom)) {
try {
value = JSON.parse(initialCollectCoverageFrom);
} catch {}
if (options[key] && !Array.isArray(value)) {
value = [initialCollectCoverageFrom];
}
} else {
value = initialCollectCoverageFrom;
}
if (value) {
value = value.map(filePath =>
filePath.replace(/^(!?)(<rootDir>\/)(.*)/, '$1$3')
);
}
return value;
};
const normalizeUnmockedModulePathPatterns = (
options,
key // _replaceRootDirTags is specifically well-suited for substituting
) =>
// <rootDir> in paths (it deals with properly interpreting relative path
// separators, etc).
//
// For patterns, direct global substitution is far more ideal, so we
// special case substitutions for patterns here.
options[key].map(pattern =>
(0, _jestRegexUtil().replacePathSepForRegex)(
pattern.replace(/<rootDir>/g, options.rootDir)
)
);
const normalizePreprocessor = options => {
if (options.scriptPreprocessor && options.transform) {
throw createConfigError(` Options: ${_chalk().default.bold(
'scriptPreprocessor'
)} and ${_chalk().default.bold('transform')} cannot be used together.
Please change your configuration to only use ${_chalk().default.bold(
'transform'
)}.`);
}
if (options.preprocessorIgnorePatterns && options.transformIgnorePatterns) {
throw createConfigError(` Options ${_chalk().default.bold(
'preprocessorIgnorePatterns'
)} and ${_chalk().default.bold(
'transformIgnorePatterns'
)} cannot be used together.
Please change your configuration to only use ${_chalk().default.bold(
'transformIgnorePatterns'
)}.`);
}
if (options.scriptPreprocessor) {
options.transform = {
'.*': options.scriptPreprocessor
};
}
if (options.preprocessorIgnorePatterns) {
options.transformIgnorePatterns = options.preprocessorIgnorePatterns;
}
delete options.scriptPreprocessor;
delete options.preprocessorIgnorePatterns;
return options;
};
const normalizeMissingOptions = (options, configPath, projectIndex) => {
if (!options.name) {
options.name = (0, _crypto().createHash)('md5')
.update(options.rootDir) // In case we load config from some path that has the same root dir
.update(configPath || '')
.update(String(projectIndex))
.digest('hex');
}
if (!options.setupFiles) {
options.setupFiles = [];
}
return options;
};
const normalizeRootDir = options => {
// Assert that there *is* a rootDir
if (!options.rootDir) {
throw createConfigError(
` Configuration option ${_chalk().default.bold(
'rootDir'
)} must be specified.`
);
}
options.rootDir = path().normalize(options.rootDir);
try {
// try to resolve windows short paths, ignoring errors (permission errors, mostly)
options.rootDir = (0, _jestUtil().tryRealpath)(options.rootDir);
} catch {
// ignored
}
verifyDirectoryExists(options.rootDir, 'rootDir');
return {...options, rootDir: options.rootDir};
};
const normalizeReporters = options => {
const reporters = options.reporters;
if (!reporters || !Array.isArray(reporters)) {
return options;
}
(0, _ReporterValidationErrors.validateReporters)(reporters);
options.reporters = reporters.map(reporterConfig => {
const normalizedReporterConfig =
typeof reporterConfig === 'string' // if reporter config is a string, we wrap it in an array
? // and pass an empty object for options argument, to normalize
// the shape.
[reporterConfig, {}]
: reporterConfig;
const reporterPath = (0, _utils.replaceRootDirInPath)(
options.rootDir,
normalizedReporterConfig[0]
);
if (reporterPath !== _constants.DEFAULT_REPORTER_LABEL) {
const reporter = _jestResolve().default.findNodeModule(reporterPath, {
basedir: options.rootDir
});
if (!reporter) {
throw new (_jestResolve().default.ModuleNotFoundError)(
'Could not resolve a module for a custom reporter.\n' +
` Module name: ${reporterPath}`
);
}
normalizedReporterConfig[0] = reporter;
}
return normalizedReporterConfig;
});
return options;
};
const buildTestPathPattern = argv => {
const patterns = [];
if (argv._) {
patterns.push(...argv._);
}
if (argv.testPathPattern) {
patterns.push(...argv.testPathPattern);
}
const replacePosixSep = pattern => {
// yargs coerces positional args into numbers
const patternAsString = pattern.toString();
if (path().sep === '/') {
return patternAsString;
}
return patternAsString.replace(/\//g, '\\\\');
};
const testPathPattern = patterns.map(replacePosixSep).join('|');
if ((0, _validatePattern.default)(testPathPattern)) {
return testPathPattern;
} else {
showTestPathPatternError(testPathPattern);
return '';
}
};
const showTestPathPatternError = testPathPattern => {
(0, _jestUtil().clearLine)(process.stdout); // eslint-disable-next-line no-console
console.log(
_chalk().default.red(
` Invalid testPattern ${testPathPattern} supplied. ` +
'Running all tests instead.'
)
);
};
function validateExtensionsToTreatAsEsm(extensionsToTreatAsEsm) {
if (!extensionsToTreatAsEsm || extensionsToTreatAsEsm.length === 0) {
return;
}
function printConfig(opts) {
const string = opts.map(ext => `'${ext}'`).join(', ');
return _chalk().default.bold(`extensionsToTreatAsEsm: [${string}]`);
}
const extensionWithoutDot = extensionsToTreatAsEsm.some(
ext => !ext.startsWith('.')
);
if (extensionWithoutDot) {
throw createConfigError(` Option: ${printConfig(
extensionsToTreatAsEsm
)} includes a string that does not start with a period (${_chalk().default.bold(
'.'
)}).
Please change your configuration to ${printConfig(
extensionsToTreatAsEsm.map(ext => (ext.startsWith('.') ? ext : `.${ext}`))
)}.`);
}
if (extensionsToTreatAsEsm.includes('.js')) {
throw createConfigError(
` Option: ${printConfig(
extensionsToTreatAsEsm
)} includes ${_chalk().default.bold(
"'.js'"
)} which is always inferred based on ${_chalk().default.bold(
'type'
)} in its nearest ${_chalk().default.bold('package.json')}.`
);
}
if (extensionsToTreatAsEsm.includes('.cjs')) {
throw createConfigError(
` Option: ${printConfig(
extensionsToTreatAsEsm
)} includes ${_chalk().default.bold(
"'.cjs'"
)} which is always treated as CommonJS.`
);
}
if (extensionsToTreatAsEsm.includes('.mjs')) {
throw createConfigError(
` Option: ${printConfig(
extensionsToTreatAsEsm
)} includes ${_chalk().default.bold(
"'.mjs'"
)} which is always treated as an ECMAScript Module.`
);
}
}
async function normalize(
initialOptions,
argv,
configPath,
projectIndex = Infinity
) {
var _options$haste, _argv$_;
const {hasDeprecationWarnings} = (0, _jestValidate().validate)(
initialOptions,
{
comment: _utils.DOCUMENTATION_NOTE,
deprecatedConfig: _Deprecated.default,
exampleConfig: _ValidConfig.default,
recursiveDenylist: [
'collectCoverageOnlyFrom', // 'coverageThreshold' allows to use 'global' and glob strings on the same
// level, there's currently no way we can deal with such config
'coverageThreshold',
'globals',
'moduleNameMapper',
'testEnvironmentOptions',
'transform'
]
}
);
let options = normalizePreprocessor(
normalizeReporters(
normalizeMissingOptions(
normalizeRootDir((0, _setFromArgv.default)(initialOptions, argv)),
configPath,
projectIndex
)
)
);
if (options.preset) {
options = await setupPreset(options, options.preset);
}
if (!options.setupFilesAfterEnv) {
options.setupFilesAfterEnv = [];
}
if (
options.setupTestFrameworkScriptFile &&
options.setupFilesAfterEnv.length > 0
) {
throw createConfigError(` Options: ${_chalk().default.bold(
'setupTestFrameworkScriptFile'
)} and ${_chalk().default.bold(
'setupFilesAfterEnv'
)} cannot be used together.
Please change your configuration to only use ${_chalk().default.bold(
'setupFilesAfterEnv'
)}.`);
}
if (options.setupTestFrameworkScriptFile) {
options.setupFilesAfterEnv.push(options.setupTestFrameworkScriptFile);
}
options.testEnvironment = (0, _jestResolve().resolveTestEnvironment)({
requireResolveFunction: require.resolve,
rootDir: options.rootDir,
testEnvironment:
options.testEnvironment ||
require.resolve(_Defaults.default.testEnvironment)
});
if (!options.roots && options.testPathDirs) {
options.roots = options.testPathDirs;
delete options.testPathDirs;
}
if (!options.roots) {
options.roots = [options.rootDir];
}
if (
!options.testRunner ||
options.testRunner === 'circus' ||
options.testRunner === 'jest-circus'
) {
options.testRunner = require.resolve('jest-circus/runner');
} else if (options.testRunner === 'jasmine2') {
options.testRunner = require.resolve('jest-jasmine2');
}
if (!options.coverageDirectory) {
options.coverageDirectory = path().resolve(options.rootDir, 'coverage');
}
setupBabelJest(options); // TODO: Type this properly
const newOptions = {..._Defaults.default};
if (options.resolver) {
newOptions.resolver = (0, _utils.resolve)(null, {
filePath: options.resolver,
key: 'resolver',
rootDir: options.rootDir
});
}
validateExtensionsToTreatAsEsm(options.extensionsToTreatAsEsm);
if (options.watchman == null) {
options.watchman = _Defaults.default.watchman;
}
const optionKeys = Object.keys(options);
optionKeys.reduce((newOptions, key) => {
// The resolver has been resolved separately; skip it
if (key === 'resolver') {
return newOptions;
} // This is cheating, because it claims that all keys of InitialOptions are Required.
// We only really know it's Required for oldOptions[key], not for oldOptions.someOtherKey,
// so oldOptions[key] is the only way it should be used.
const oldOptions = options;
let value;
switch (key) {
case 'collectCoverageOnlyFrom':
value = normalizeCollectCoverageOnlyFrom(oldOptions, key);
break;
case 'setupFiles':
case 'setupFilesAfterEnv':
case 'snapshotSerializers':
{
const option = oldOptions[key];
value =
option &&
option.map(filePath =>
(0, _utils.resolve)(newOptions.resolver, {
filePath,
key,
rootDir: options.rootDir
})
);
}
break;
case 'modulePaths':
case 'roots':
{
const option = oldOptions[key];
value =
option &&
option.map(filePath =>
path().resolve(
options.rootDir,
(0, _utils.replaceRootDirInPath)(options.rootDir, filePath)
)
);
}
break;
case 'collectCoverageFrom':
value = normalizeCollectCoverageFrom(oldOptions, key);
break;
case 'cacheDirectory':
case 'coverageDirectory':
{
const option = oldOptions[key];
value =
option &&
path().resolve(
options.rootDir,
(0, _utils.replaceRootDirInPath)(options.rootDir, option)
);
}
break;
case 'dependencyExtractor':
case 'globalSetup':
case 'globalTeardown':
case 'moduleLoader':
case 'snapshotResolver':
case 'testResultsProcessor':
case 'testRunner':
case 'filter':
{
const option = oldOptions[key];
value =
option &&
(0, _utils.resolve)(newOptions.resolver, {
filePath: option,
key,
rootDir: options.rootDir
});
}
break;
case 'runner':
{
const option = oldOptions[key];
value =
option &&
(0, _jestResolve().resolveRunner)(newOptions.resolver, {
filePath: option,
requireResolveFunction: require.resolve,
rootDir: options.rootDir
});
}
break;
case 'prettierPath':
{
// We only want this to throw if "prettierPath" is explicitly passed
// from config or CLI, and the requested path isn't found. Otherwise we
// set it to null and throw an error lazily when it is used.
const option = oldOptions[key];
value =
option &&
(0, _utils.resolve)(newOptions.resolver, {
filePath: option,
key,
optional: option === _Defaults.default[key],
rootDir: options.rootDir
});
}
break;
case 'moduleNameMapper':
const moduleNameMapper = oldOptions[key];
value =
moduleNameMapper &&
Object.keys(moduleNameMapper).map(regex => {
const item = moduleNameMapper && moduleNameMapper[regex];
return (
item && [
regex,
(0, _utils._replaceRootDirTags)(options.rootDir, item)
]
);
});
break;
case 'transform':
const transform = oldOptions[key];
value =
transform &&
Object.keys(transform).map(regex => {
const transformElement = transform[regex];
return [
regex,
(0, _utils.resolve)(newOptions.resolver, {
filePath: Array.isArray(transformElement)
? transformElement[0]
: transformElement,
key,
rootDir: options.rootDir
}),
Array.isArray(transformElement) ? transformElement[1] : {}
];
});
break;
case 'coveragePathIgnorePatterns':
case 'modulePathIgnorePatterns':
case 'testPathIgnorePatterns':
case 'transformIgnorePatterns':
case 'watchPathIgnorePatterns':
case 'unmockedModulePathPatterns':
value = normalizeUnmockedModulePathPatterns(oldOptions, key);
break;
case 'haste':
value = {...oldOptions[key]};
if (value.hasteImplModulePath != null) {
const resolvedHasteImpl = (0, _utils.resolve)(newOptions.resolver, {
filePath: (0, _utils.replaceRootDirInPath)(
options.rootDir,
value.hasteImplModulePath
),
key: 'haste.hasteImplModulePath',
rootDir: options.rootDir
});
value.hasteImplModulePath = resolvedHasteImpl || undefined;
}
break;
case 'projects':
value = (oldOptions[key] || [])
.map(project =>
typeof project === 'string'
? (0, _utils._replaceRootDirTags)(options.rootDir, project)
: project
)
.reduce((projects, project) => {
// Project can be specified as globs. If a glob matches any files,
// We expand it to these paths. If not, we keep the original path
// for the future resolution.
const globMatches =
typeof project === 'string' ? (0, _glob().sync)(project) : [];
return projects.concat(globMatches.length ? globMatches : project);
}, []);
break;
case 'moduleDirectories':
case 'testMatch':
{
const replacedRootDirTags = (0, _utils._replaceRootDirTags)(
(0, _utils.escapeGlobCharacters)(options.rootDir),
oldOptions[key]
);
if (replacedRootDirTags) {
value = Array.isArray(replacedRootDirTags)
? replacedRootDirTags.map(_jestUtil().replacePathSepForGlob)
: (0, _jestUtil().replacePathSepForGlob)(replacedRootDirTags);
} else {
value = replacedRootDirTags;
}
}
break;
case 'testRegex':
{
const option = oldOptions[key];
value = option
? (Array.isArray(option) ? option : [option]).map(
_jestRegexUtil().replacePathSepForRegex
)
: [];
}
break;
case 'moduleFileExtensions': {
value = oldOptions[key];
if (
Array.isArray(value) && // If it's the wrong type, it can throw at a later time
(options.runner === undefined ||
options.runner === _Defaults.default.runner) && // Only require 'js' for the default jest-runner
!value.includes('js')
) {
const errorMessage =
" moduleFileExtensions must include 'js':\n" +
' but instead received:\n' +
` ${_chalk().default.bold.red(JSON.stringify(value))}`; // If `js` is not included, any dependency Jest itself injects into
// the environment, like jasmine or sourcemap-support, will need to
// `require` its modules with a file extension. This is not plausible
// in the long run, so it's way easier to just fail hard early.
// We might consider throwing if `json` is missing as well, as it's a
// fair assumption from modules that they can do
// `require('some-package/package') without the trailing `.json` as it
// works in Node normally.
throw createConfigError(
errorMessage +
"\n Please change your configuration to include 'js'."
);
}
break;
}
case 'bail': {
const bail = oldOptions[key];
if (typeof bail === 'boolean') {
value = bail ? 1 : 0;
} else if (typeof bail === 'string') {
value = 1; // If Jest is invoked as `jest --bail someTestPattern` then need to
// move the pattern from the `bail` configuration and into `argv._`
// to be processed as an extra parameter
argv._.push(bail);
} else {
value = oldOptions[key];
}
break;
}
case 'displayName': {
const displayName = oldOptions[key];
/**
* Ensuring that displayName shape is correct here so that the
* reporters can trust the shape of the data
*/
if (typeof displayName === 'object') {
const {name, color} = displayName;
if (
!name ||
!color ||
typeof name !== 'string' ||
typeof color !== 'string'
) {
const errorMessage =
` Option "${_chalk().default.bold(
'displayName'
)}" must be of type:\n\n` +
' {\n' +
' name: string;\n' +
' color: string;\n' +
' }\n';
throw createConfigError(errorMessage);
}
value = oldOptions[key];
} else {
value = {
color: (0, _color.getDisplayNameColor)(options.runner),
name: displayName
};
}
break;
}
case 'testTimeout': {
if (oldOptions[key] < 0) {
throw createConfigError(
` Option "${_chalk().default.bold(
'testTimeout'
)}" must be a natural number.`
);
}
value = oldOptions[key];
break;
}
case 'automock':
case 'cache':
case 'changedSince':
case 'changedFilesWithAncestor':
case 'clearMocks':
case 'collectCoverage':
case 'coverageProvider':
case 'coverageReporters':
case 'coverageThreshold':
case 'detectLeaks':
case 'detectOpenHandles':
case 'errorOnDeprecated':
case 'expand':
case 'extensionsToTreatAsEsm':
case 'extraGlobals':
case 'globals':
case 'findRelatedTests':
case 'forceCoverageMatch':
case 'forceExit':
case 'injectGlobals':
case 'lastCommit':
case 'listTests':
case 'logHeapUsage':
case 'maxConcurrency':
case 'name':
case 'noStackTrace':
case 'notify':
case 'notifyMode':
case 'onlyChanged':
case 'onlyFailures':
case 'outputFile':
case 'passWithNoTests':
case 'replname':
case 'reporters':
case 'resetMocks':
case 'resetModules':
case 'restoreMocks':
case 'rootDir':
case 'runTestsByPath':
case 'silent':
case 'skipFilter':
case 'skipNodeResolution':
case 'slowTestThreshold':
case 'snapshotFormat':
case 'testEnvironment':
case 'testEnvironmentOptions':
case 'testFailureExitCode':
case 'testLocationInResults':
case 'testNamePattern':
case 'testURL':
case 'timers':
case 'useStderr':
case 'verbose':
case 'watch':
case 'watchAll':
case 'watchman':
value = oldOptions[key];
break;
case 'watchPlugins':
value = (oldOptions[key] || []).map(watchPlugin => {
if (typeof watchPlugin === 'string') {
return {
config: {},
path: (0, _jestResolve().resolveWatchPlugin)(
newOptions.resolver,
{
filePath: watchPlugin,
requireResolveFunction: require.resolve,
rootDir: options.rootDir
}
)
};
} else {
return {
config: watchPlugin[1] || {},
path: (0, _jestResolve().resolveWatchPlugin)(
newOptions.resolver,
{
filePath: watchPlugin[0],
requireResolveFunction: require.resolve,
rootDir: options.rootDir
}
)
};
}
});
break;
} // @ts-expect-error: automock is missing in GlobalConfig, so what
newOptions[key] = value;
return newOptions;
}, newOptions);
if (
options.watchman &&
(_options$haste = options.haste) !== null &&
_options$haste !== void 0 &&
_options$haste.enableSymlinks
) {
throw new (_jestValidate().ValidationError)(
'Validation Error',
'haste.enableSymlinks is incompatible with watchman',
'Either set haste.enableSymlinks to false or do not use watchman'
);
}
newOptions.roots.forEach((root, i) => {
verifyDirectoryExists(root, `roots[${i}]`);
});
try {
// try to resolve windows short paths, ignoring errors (permission errors, mostly)
newOptions.cwd = (0, _jestUtil().tryRealpath)(process.cwd());
} catch {
// ignored
}
newOptions.testSequencer = (0, _jestResolve().resolveSequencer)(
newOptions.resolver,
{
filePath:
options.testSequencer ||
require.resolve(_Defaults.default.testSequencer),
requireResolveFunction: require.resolve,
rootDir: options.rootDir
}
);
if (newOptions.runner === _Defaults.default.runner) {
newOptions.runner = require.resolve(newOptions.runner);
}
newOptions.nonFlagArgs =
(_argv$_ = argv._) === null || _argv$_ === void 0
? void 0
: _argv$_.map(arg => `${arg}`);
newOptions.testPathPattern = buildTestPathPattern(argv);
newOptions.json = !!argv.json;
newOptions.testFailureExitCode = parseInt(newOptions.testFailureExitCode, 10);
if (
newOptions.lastCommit ||
newOptions.changedFilesWithAncestor ||
newOptions.changedSince
) {
newOptions.onlyChanged = true;
}
if (argv.all) {
newOptions.onlyChanged = false;
newOptions.onlyFailures = false;
} else if (newOptions.testPathPattern) {
// When passing a test path pattern we don't want to only monitor changed
// files unless `--watch` is also passed.
newOptions.onlyChanged = newOptions.watch;
}
if (!newOptions.onlyChanged) {
newOptions.onlyChanged = false;
}
if (!newOptions.lastCommit) {
newOptions.lastCommit = false;
}
if (!newOptions.onlyFailures) {
newOptions.onlyFailures = false;
}
if (!newOptions.watchAll) {
newOptions.watchAll = false;
} // as unknown since it can happen. We really need to fix the types here
if (newOptions.moduleNameMapper === _Defaults.default.moduleNameMapper) {
newOptions.moduleNameMapper = [];
}
newOptions.updateSnapshot =
argv.ci && !argv.updateSnapshot
? 'none'
: argv.updateSnapshot
? 'all'
: 'new';
newOptions.maxConcurrency = parseInt(newOptions.maxConcurrency, 10);
newOptions.maxWorkers = (0, _getMaxWorkers.default)(argv, options);
if (newOptions.testRegex.length && options.testMatch) {
throw createConfigError(
` Configuration options ${_chalk().default.bold('testMatch')} and` +
` ${_chalk().default.bold('testRegex')} cannot be used together.`
);
}
if (newOptions.testRegex.length && !options.testMatch) {
// Prevent the default testMatch conflicting with any explicitly
// configured `testRegex` value
newOptions.testMatch = [];
} // If argv.json is set, coverageReporters shouldn't print a text report.
if (argv.json) {
newOptions.coverageReporters = (newOptions.coverageReporters || []).filter(
reporter => reporter !== 'text'
);
} // If collectCoverage is enabled while using --findRelatedTests we need to
// avoid having false negatives in the generated coverage report.
// The following: `--findRelatedTests '/rootDir/file1.js' --coverage`
// Is transformed to: `--findRelatedTests '/rootDir/file1.js' --coverage --collectCoverageFrom 'file1.js'`
// where arguments to `--collectCoverageFrom` should be globs (or relative
// paths to the rootDir)
if (newOptions.collectCoverage && argv.findRelatedTests) {
let collectCoverageFrom = newOptions.nonFlagArgs.map(filename => {
filename = (0, _utils.replaceRootDirInPath)(options.rootDir, filename);
return path().isAbsolute(filename)
? path().relative(options.rootDir, filename)
: filename;
}); // Don't override existing collectCoverageFrom options
if (newOptions.collectCoverageFrom) {
collectCoverageFrom = collectCoverageFrom.reduce((patterns, filename) => {
if (
(0, _micromatch().default)(
[
(0, _jestUtil().replacePathSepForGlob)(
path().relative(options.rootDir, filename)
)
],
newOptions.collectCoverageFrom
).length === 0
) {
return patterns;
}
return [...patterns, filename];
}, newOptions.collectCoverageFrom);
}
newOptions.collectCoverageFrom = collectCoverageFrom;
} else if (!newOptions.collectCoverageFrom) {
newOptions.collectCoverageFrom = [];
}
if (!newOptions.findRelatedTests) {
newOptions.findRelatedTests = false;
}
if (!newOptions.projects) {
newOptions.projects = [];
}
if (!newOptions.extraGlobals) {
newOptions.extraGlobals = [];
}
if (!newOptions.forceExit) {
newOptions.forceExit = false;
}
if (!newOptions.logHeapUsage) {
newOptions.logHeapUsage = false;
}
return {
hasDeprecationWarnings,
options: newOptions
};
}