normalize.js 34 KB

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