-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
normalize.ts
1179 lines (1065 loc) · 34.4 KB
/
normalize.ts
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {createHash} from 'crypto';
import {totalmem} from 'os';
import * as path from 'path';
import chalk = require('chalk');
import merge = require('deepmerge');
import {glob} from 'glob';
import {statSync} from 'graceful-fs';
import micromatch = require('micromatch');
import {TestPathPatterns} from '@jest/pattern';
import type {Config} from '@jest/types';
import {replacePathSepForRegex} from 'jest-regex-util';
import Resolver, {
resolveRunner,
resolveSequencer,
resolveTestEnvironment,
resolveWatchPlugin,
} from 'jest-resolve';
import {
clearLine,
replacePathSepForGlob,
requireOrImportModule,
tryRealpath,
} from 'jest-util';
import {ValidationError, validate} from 'jest-validate';
import DEFAULT_CONFIG from './Defaults';
import DEPRECATED_CONFIG from './Deprecated';
import {validateReporters} from './ReporterValidationErrors';
import {
initialOptions as VALID_CONFIG,
initialProjectOptions as VALID_PROJECT_CONFIG,
} from './ValidConfig';
import {getDisplayNameColor} from './color';
import {DEFAULT_JS_PATTERN} from './constants';
import getMaxWorkers from './getMaxWorkers';
import {parseShardPair} from './parseShardPair';
import setFromArgv from './setFromArgv';
import stringToBytes from './stringToBytes';
import {
BULLET,
DOCUMENTATION_NOTE,
_replaceRootDirTags,
escapeGlobCharacters,
replaceRootDirInPath,
resolve,
} from './utils';
const ERROR = `${BULLET}Validation Error`;
const PRESET_EXTENSIONS = ['.json', '.js', '.cjs', '.mjs'];
const PRESET_NAME = 'jest-preset';
export type AllOptions = Config.ProjectConfig & Config.GlobalConfig;
const createConfigError = (message: string) =>
new ValidationError(ERROR, message, DOCUMENTATION_NOTE);
// we wanna avoid webpack trying to be clever
const requireResolve = (module: string) => require.resolve(module);
function verifyDirectoryExists(path: string, key: string) {
try {
const rootStat = statSync(path);
if (!rootStat.isDirectory()) {
throw createConfigError(
` ${chalk.bold(path)} in the ${chalk.bold(
key,
)} option is not a directory.`,
);
}
} catch (error: any) {
if (error instanceof ValidationError) {
throw error;
}
if (error.code === 'ENOENT') {
throw createConfigError(
` Directory ${chalk.bold(path)} in the ${chalk.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.bold(path)} in the ${chalk.bold(
key,
)} option.\n\n Error was: ${error.message}`,
);
}
}
const mergeOptionWithPreset = <T extends 'moduleNameMapper' | 'transform'>(
options: Config.InitialOptions,
preset: Config.InitialOptions,
optionName: T,
) => {
if (options[optionName] && preset[optionName]) {
options[optionName] = {
...options[optionName],
...preset[optionName],
...options[optionName],
};
}
};
const mergeGlobalsWithPreset = (
options: Config.InitialOptions,
preset: Config.InitialOptions,
) => {
if (options.globals && preset.globals) {
options.globals = merge(preset.globals, options.globals);
}
};
const setupPreset = async (
options: Config.InitialOptionsWithRootDir,
optionsPreset: string,
): Promise<Config.InitialOptionsWithRootDir> => {
let preset: Config.InitialOptions;
const presetPath = replaceRootDirInPath(options.rootDir, optionsPreset);
const presetModule = Resolver.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 requireOrImportModule(presetModule);
} catch (error: any) {
if (error instanceof SyntaxError || error instanceof TypeError) {
throw createConfigError(
` Preset ${chalk.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 = Resolver.findNodeModule(presetPath, {
basedir: options.rootDir,
});
if (preset) {
throw createConfigError(
` Module ${chalk.bold(
presetPath,
)} should have "jest-preset.js" or "jest-preset.json" file at the root.`,
);
}
throw createConfigError(
` Preset ${chalk.bold(presetPath)} not found relative to rootDir ${chalk.bold(options.rootDir)}.`,
);
}
throw createConfigError(
` Missing dependency in ${chalk.bold(presetPath)}:\n\n ${
error.message
}\n ${error.stack}`,
);
}
throw createConfigError(
` An unknown error occurred in ${chalk.bold(presetPath)}:\n\n ${
error.message
}\n ${error.stack}`,
);
}
if (options.setupFiles) {
options.setupFiles = [...(preset.setupFiles || []), ...options.setupFiles];
}
if (options.setupFilesAfterEnv) {
options.setupFilesAfterEnv = [
...(preset.setupFilesAfterEnv || []),
...options.setupFilesAfterEnv,
];
}
if (options.modulePathIgnorePatterns && preset.modulePathIgnorePatterns) {
options.modulePathIgnorePatterns = [
...preset.modulePathIgnorePatterns,
...options.modulePathIgnorePatterns,
];
}
mergeOptionWithPreset(options, preset, 'moduleNameMapper');
mergeOptionWithPreset(options, preset, 'transform');
mergeGlobalsWithPreset(options, preset);
return {...preset, ...options};
};
const setupBabelJest = (options: Config.InitialOptionsWithRootDir) => {
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');
});
for (const pattern of [customJSPattern, customTSPattern]) {
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 = {
[DEFAULT_JS_PATTERN]: babelJest,
};
}
};
const normalizeCollectCoverageFrom = (
options: Config.InitialOptions &
Required<Pick<Config.InitialOptions, 'collectCoverageFrom'>>,
key: keyof Pick<Config.InitialOptions, 'collectCoverageFrom'>,
) => {
const initialCollectCoverageFrom = options[key];
let value: Array<string> | undefined;
if (!initialCollectCoverageFrom) {
value = [];
}
if (Array.isArray(initialCollectCoverageFrom)) {
value = initialCollectCoverageFrom;
} else {
try {
value = JSON.parse(initialCollectCoverageFrom);
} catch {}
if (options[key] && !Array.isArray(value)) {
value = [initialCollectCoverageFrom];
}
}
if (value) {
value = value.map(filePath =>
filePath.replace(/^(!?)(<rootDir>\/)(.*)/, '$1$3'),
);
}
return value;
};
const normalizeUnmockedModulePathPatterns = (
options: Config.InitialOptionsWithRootDir,
key: keyof Pick<
Config.InitialOptions,
| 'coveragePathIgnorePatterns'
| 'modulePathIgnorePatterns'
| 'testPathIgnorePatterns'
| 'transformIgnorePatterns'
| 'watchPathIgnorePatterns'
| 'unmockedModulePathPatterns'
>,
) =>
// _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 =>
replacePathSepForRegex(pattern.replaceAll('<rootDir>', options.rootDir)),
);
const normalizeMissingOptions = (
options: Config.InitialOptionsWithRootDir,
configPath: string | null | undefined,
projectIndex: number,
): Config.InitialOptionsWithRootDir => {
if (!options.id) {
options.id = createHash('sha1')
.update(options.rootDir)
// In case we load config from some path that has the same root dir
.update(configPath || '')
.update(String(projectIndex))
.digest('hex')
.slice(0, 32);
}
if (!options.setupFiles) {
options.setupFiles = [];
}
return options;
};
const normalizeRootDir = (
options: Config.InitialOptions,
): Config.InitialOptionsWithRootDir => {
// Assert that there *is* a rootDir
if (!options.rootDir) {
throw createConfigError(
` Configuration option ${chalk.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 = tryRealpath(options.rootDir);
} catch {
// ignored
}
verifyDirectoryExists(options.rootDir, 'rootDir');
return {
...options,
rootDir: options.rootDir,
};
};
const normalizeReporters = ({
reporters,
rootDir,
}: Config.InitialOptionsWithRootDir):
| Array<Config.ReporterConfig>
| undefined => {
if (!reporters || !Array.isArray(reporters)) {
return undefined;
}
validateReporters(reporters);
return reporters.map(reporterConfig => {
const normalizedReporterConfig: Config.ReporterConfig =
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 = replaceRootDirInPath(
rootDir,
normalizedReporterConfig[0],
);
if (!['default', 'github-actions', 'summary'].includes(reporterPath)) {
const reporter = Resolver.findNodeModule(reporterPath, {
basedir: rootDir,
});
if (!reporter) {
throw new Resolver.ModuleNotFoundError(
'Could not resolve a module for a custom reporter.\n' +
` Module name: ${reporterPath}`,
);
}
normalizedReporterConfig[0] = reporter;
}
return normalizedReporterConfig;
});
};
const buildTestPathPatterns = (argv: Config.Argv): TestPathPatterns => {
const patterns = [];
if (argv._) {
patterns.push(...argv._.map(x => x.toString()));
}
if (argv.testPathPatterns) {
patterns.push(...argv.testPathPatterns);
}
const testPathPatterns = new TestPathPatterns(patterns);
if (!testPathPatterns.isValid()) {
clearLine(process.stdout);
// eslint-disable-next-line no-console
console.log(
chalk.red(
` Invalid testPattern ${testPathPatterns.toPretty()} supplied. ` +
'Running all tests instead.',
),
);
return new TestPathPatterns([]);
}
return testPathPatterns;
};
function printConfig(opts: Array<string>) {
const string = opts.map(ext => `'${ext}'`).join(', ');
return chalk.bold(`extensionsToTreatAsEsm: [${string}]`);
}
function validateExtensionsToTreatAsEsm(
extensionsToTreatAsEsm: Config.InitialOptions['extensionsToTreatAsEsm'],
) {
if (!extensionsToTreatAsEsm || extensionsToTreatAsEsm.length === 0) {
return;
}
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.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.bold(
"'.js'",
)} which is always inferred based on ${chalk.bold(
'type',
)} in its nearest ${chalk.bold('package.json')}.`,
);
}
if (extensionsToTreatAsEsm.includes('.cjs')) {
throw createConfigError(
` Option: ${printConfig(extensionsToTreatAsEsm)} includes ${chalk.bold(
"'.cjs'",
)} which is always treated as CommonJS.`,
);
}
if (extensionsToTreatAsEsm.includes('.mjs')) {
throw createConfigError(
` Option: ${printConfig(extensionsToTreatAsEsm)} includes ${chalk.bold(
"'.mjs'",
)} which is always treated as an ECMAScript Module.`,
);
}
}
export default async function normalize(
initialOptions: Config.InitialOptions,
argv: Config.Argv,
configPath?: string | null,
projectIndex = Number.POSITIVE_INFINITY,
isProjectOptions?: boolean,
): Promise<{
hasDeprecationWarnings: boolean;
options: AllOptions;
}> {
const {hasDeprecationWarnings} = validate(initialOptions, {
comment: DOCUMENTATION_NOTE,
deprecatedConfig: DEPRECATED_CONFIG,
exampleConfig: isProjectOptions ? VALID_PROJECT_CONFIG : VALID_CONFIG,
recursiveDenylist: [
// '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 = normalizeMissingOptions(
normalizeRootDir(setFromArgv(initialOptions, argv)),
configPath,
projectIndex,
);
if (options.preset) {
options = await setupPreset(options, options.preset);
}
if (!options.setupFilesAfterEnv) {
options.setupFilesAfterEnv = [];
}
options.testEnvironment = resolveTestEnvironment({
requireResolveFunction: requireResolve,
rootDir: options.rootDir,
testEnvironment:
options.testEnvironment ||
require.resolve(DEFAULT_CONFIG.testEnvironment),
});
if (!options.roots) {
options.roots = [options.rootDir];
}
if (
!options.testRunner ||
options.testRunner === 'circus' ||
options.testRunner === 'jest-circus' ||
options.testRunner === 'jest-circus/runner'
) {
options.testRunner = require.resolve('jest-circus/runner');
} else if (options.testRunner === 'jasmine2') {
try {
options.testRunner = require.resolve('jest-jasmine2');
} catch (error: any) {
if (error.code === 'MODULE_NOT_FOUND') {
throw createConfigError(
'jest-jasmine is no longer shipped by default with Jest, you need to install it explicitly or provide an absolute path to Jest',
);
}
throw error;
}
}
if (!options.coverageDirectory) {
options.coverageDirectory = path.resolve(options.rootDir, 'coverage');
}
setupBabelJest(options);
// TODO: Type this properly
const newOptions = {
...DEFAULT_CONFIG,
} as unknown as AllOptions;
if (options.resolver) {
newOptions.resolver = resolve(null, {
filePath: options.resolver,
key: 'resolver',
rootDir: options.rootDir,
});
}
validateExtensionsToTreatAsEsm(options.extensionsToTreatAsEsm);
if (options.watchman == null) {
options.watchman = DEFAULT_CONFIG.watchman;
}
const optionKeys = Object.keys(options) as Array<keyof Config.InitialOptions>;
optionKeys.reduce((newOptions, key: keyof Config.InitialOptions) => {
// 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 as Config.InitialOptions &
Required<Pick<Config.InitialOptions, typeof key>>;
let value;
switch (key) {
case 'setupFiles':
case 'setupFilesAfterEnv':
case 'snapshotSerializers':
{
const option = oldOptions[key];
value =
option &&
option.map(filePath =>
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,
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,
replaceRootDirInPath(options.rootDir, option),
);
}
break;
case 'dependencyExtractor':
case 'globalSetup':
case 'globalTeardown':
case 'runtime':
case 'snapshotResolver':
case 'testResultsProcessor':
case 'testRunner':
case 'filter':
{
const option = oldOptions[key];
value =
option &&
resolve(newOptions.resolver, {
filePath: option,
key,
rootDir: options.rootDir,
});
}
break;
case 'runner':
{
const option = oldOptions[key];
value =
option &&
resolveRunner(newOptions.resolver, {
filePath: option,
requireResolveFunction: requireResolve,
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 &&
resolve(newOptions.resolver, {
filePath: option,
key,
optional: option === DEFAULT_CONFIG[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, _replaceRootDirTags(options.rootDir, item)];
});
break;
case 'transform':
const transform = oldOptions[key];
value =
transform &&
Object.keys(transform).map(regex => {
const transformElement = transform[regex];
return [
regex,
resolve(newOptions.resolver, {
filePath: Array.isArray(transformElement)
? transformElement[0]
: transformElement,
key,
rootDir: options.rootDir,
}),
Array.isArray(transformElement) ? transformElement[1] : {},
];
});
break;
case 'reporters':
value = normalizeReporters(oldOptions);
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 = resolve(newOptions.resolver, {
filePath: 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'
? _replaceRootDirTags(options.rootDir, project)
: project,
)
.reduce<Array<string | Config.InitialProjectOptions>>(
(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'
? glob.sync(project, {windowsPathsNoEscape: true})
: [];
const projectEntry =
globMatches.length > 0 ? globMatches : project;
return [
...projects,
...(Array.isArray(projectEntry)
? projectEntry
: [projectEntry]),
];
},
[],
);
break;
case 'moduleDirectories':
case 'testMatch':
{
const replacedRootDirTags = _replaceRootDirTags(
escapeGlobCharacters(options.rootDir),
oldOptions[key],
);
if (replacedRootDirTags) {
value = Array.isArray(replacedRootDirTags)
? replacedRootDirTags.map(replacePathSepForGlob)
: replacePathSepForGlob(replacedRootDirTags);
} else {
value = replacedRootDirTags;
}
}
break;
case 'testRegex':
{
const option = oldOptions[key];
value = option
? (Array.isArray(option) ? option : [option]).map(
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 === DEFAULT_CONFIG.runner) && // Only require 'js' for the default jest-runner
!value.includes('js')
) {
const errorMessage =
" moduleFileExtensions must include 'js':\n" +
' but instead received:\n' +
` ${chalk.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] as Config.DisplayName;
/**
* 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.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: getDisplayNameColor(options.runner),
name: displayName,
};
}
break;
}
case 'testTimeout': {
if (oldOptions[key] < 0) {
throw createConfigError(
` Option "${chalk.bold('testTimeout')}" must be a natural number.`,
);
}
value = oldOptions[key];
break;
}
case 'snapshotFormat': {
value = {...DEFAULT_CONFIG.snapshotFormat, ...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 'globals':
case 'fakeTimers':
case 'findRelatedTests':
case 'forceCoverageMatch':
case 'forceExit':
case 'injectGlobals':
case 'lastCommit':
case 'listTests':
case 'logHeapUsage':
case 'maxConcurrency':
case 'id':
case 'noStackTrace':
case 'notify':
case 'notifyMode':
case 'onlyChanged':
case 'onlyFailures':
case 'openHandlesTimeout':
case 'outputFile':
case 'passWithNoTests':
case 'randomize':
case 'replname':
case 'resetMocks':
case 'resetModules':
case 'restoreMocks':
case 'rootDir':
case 'runTestsByPath':
case 'sandboxInjectedGlobals':
case 'silent':
case 'showSeed':
case 'skipFilter':
case 'skipNodeResolution':
case 'slowTestThreshold':
case 'testEnvironment':
case 'testEnvironmentOptions':
case 'testFailureExitCode':
case 'testLocationInResults':
case 'testNamePattern':
case 'useStderr':
case 'verbose':
case 'waitNextEventLoopTurnForUnhandledRejectionEvents':
case 'watch':
case 'watchAll':
case 'watchman':
case 'workerThreads':
value = oldOptions[key];
break;
case 'workerIdleMemoryLimit':
value = stringToBytes(oldOptions[key], totalmem());
break;
case 'watchPlugins':
value = (oldOptions[key] || []).map(watchPlugin => {
if (typeof watchPlugin === 'string') {
return {
config: {},
path: resolveWatchPlugin(newOptions.resolver, {
filePath: watchPlugin,
requireResolveFunction: requireResolve,
rootDir: options.rootDir,
}),
};
} else {
return {
config: watchPlugin[1] || {},
path: resolveWatchPlugin(newOptions.resolver, {
filePath: watchPlugin[0],
requireResolveFunction: requireResolve,
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?.enableSymlinks) {
throw new ValidationError(
'Validation Error',
'haste.enableSymlinks is incompatible with watchman',
'Either set haste.enableSymlinks to false or do not use watchman',
);
}
for (const [i, root] of newOptions.roots.entries()) {
verifyDirectoryExists(root, `roots[${i}]`);
}
try {
// try to resolve windows short paths, ignoring errors (permission errors, mostly)
newOptions.cwd = tryRealpath(process.cwd());
} catch {
// ignored
}
newOptions.testSequencer = resolveSequencer(newOptions.resolver, {
filePath:
options.testSequencer || require.resolve(DEFAULT_CONFIG.testSequencer),
requireResolveFunction: requireResolve,