UNPKG

jest-config

Version:
1,335 lines (1,258 loc) 107 kB
/*! * /** * * 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. * * / */ /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "./src/Defaults.ts": /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; function _path() { const data = require("path"); _path = function () { return data; }; return data; } function _ciInfo() { const data = require("ci-info"); _ciInfo = function () { return data; }; return data; } function _jestRegexUtil() { const data = require("jest-regex-util"); _jestRegexUtil = function () { return data; }; return data; } var _constants = __webpack_require__("./src/constants.ts"); var _getCacheDirectory = _interopRequireDefault(__webpack_require__("./src/getCacheDirectory.ts")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } /** * 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. */ const NODE_MODULES_REGEXP = (0, _jestRegexUtil().replacePathSepForRegex)(_constants.NODE_MODULES); const defaultOptions = { automock: false, bail: 0, cache: true, cacheDirectory: (0, _getCacheDirectory.default)(), changedFilesWithAncestor: false, ci: _ciInfo().isCI, clearMocks: false, collectCoverage: false, coveragePathIgnorePatterns: [NODE_MODULES_REGEXP], coverageProvider: 'babel', coverageReporters: ['json', 'text', 'lcov', 'clover'], detectLeaks: false, detectOpenHandles: false, errorOnDeprecated: false, expand: false, extensionsToTreatAsEsm: [], fakeTimers: { enableGlobally: false }, forceCoverageMatch: [], globals: {}, haste: { computeSha1: false, enableSymlinks: false, forceNodeFilesystemAPI: true, throwOnModuleCollision: false }, injectGlobals: true, listTests: false, maxConcurrency: 5, maxWorkers: '50%', moduleDirectories: ['node_modules'], moduleFileExtensions: ['js', 'mjs', 'cjs', 'jsx', 'ts', 'mts', 'cts', 'tsx', 'json', 'node'], moduleNameMapper: {}, modulePathIgnorePatterns: [], noStackTrace: false, notify: false, notifyMode: 'failure-change', openHandlesTimeout: 1000, passWithNoTests: false, prettierPath: 'prettier', resetMocks: false, resetModules: false, restoreMocks: false, roots: ['<rootDir>'], runTestsByPath: false, runner: 'jest-runner', setupFiles: [], setupFilesAfterEnv: [], skipFilter: false, slowTestThreshold: 5, snapshotFormat: { escapeString: false, printBasicPrototype: false }, snapshotSerializers: [], testEnvironment: 'jest-environment-node', testEnvironmentOptions: {}, testFailureExitCode: 1, testLocationInResults: false, testMatch: ['**/__tests__/**/*.?([mc])[jt]s?(x)', '**/?(*.)+(spec|test).?([mc])[jt]s?(x)'], testPathIgnorePatterns: [NODE_MODULES_REGEXP], testRegex: [], testRunner: 'jest-circus/runner', testSequencer: '@jest/test-sequencer', transformIgnorePatterns: [NODE_MODULES_REGEXP, `\\.pnp\\.[^\\${_path().sep}]+$`], useStderr: false, waitForUnhandledRejections: false, watch: false, watchPathIgnorePatterns: [], watchman: true, workerThreads: false }; var _default = exports["default"] = defaultOptions; /***/ }), /***/ "./src/Deprecated.ts": /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; function _chalk() { const data = _interopRequireDefault(require("chalk")); _chalk = function () { return data; }; return data; } function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } /** * 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. */ function formatDeprecation(message) { const lines = [message.replaceAll(/\*(.+?)\*/g, (_, s) => _chalk().default.bold(`"${s}"`)), '', 'Please update your configuration.']; return lines.map(s => ` ${s}`).join('\n'); } const deprecatedOptions = { browser: () => ` Option ${_chalk().default.bold('"browser"')} has been deprecated. Please install "browser-resolve" and use the "resolver" option in Jest configuration as shown in the documentation: https://jestjs.io/docs/configuration#resolver-string`, collectCoverageOnlyFrom: _options => ` Option ${_chalk().default.bold('"collectCoverageOnlyFrom"')} was replaced by ${_chalk().default.bold('"collectCoverageFrom"')}. Please update your configuration.`, extraGlobals: _options => ` Option ${_chalk().default.bold('"extraGlobals"')} was replaced by ${_chalk().default.bold('"sandboxInjectedGlobals"')}. Please update your configuration.`, init: () => ` Option ${_chalk().default.bold('"init"')} has been deprecated. Please use "create-jest" package as shown in the documentation: https://jestjs.io/docs/getting-started#generate-a-basic-configuration-file`, moduleLoader: _options => ` Option ${_chalk().default.bold('"moduleLoader"')} was replaced by ${_chalk().default.bold('"runtime"')}. Please update your configuration.`, preprocessorIgnorePatterns: _options => ` Option ${_chalk().default.bold('"preprocessorIgnorePatterns"')} was replaced by ${_chalk().default.bold('"transformIgnorePatterns"')}, which support multiple preprocessors. Please update your configuration.`, scriptPreprocessor: _options => ` Option ${_chalk().default.bold('"scriptPreprocessor"')} was replaced by ${_chalk().default.bold('"transform"')}, which support multiple preprocessors. Please update your configuration.`, setupTestFrameworkScriptFile: _options => ` Option ${_chalk().default.bold('"setupTestFrameworkScriptFile"')} was replaced by configuration ${_chalk().default.bold('"setupFilesAfterEnv"')}, which supports multiple paths. Please update your configuration.`, testPathDirs: _options => ` Option ${_chalk().default.bold('"testPathDirs"')} was replaced by ${_chalk().default.bold('"roots"')}. Please update your configuration. `, testPathPattern: () => formatDeprecation('Option *testPathPattern* was replaced by *--testPathPatterns*. *--testPathPatterns* is only available as a command-line option.'), testURL: _options => ` Option ${_chalk().default.bold('"testURL"')} was replaced by passing the URL via ${_chalk().default.bold('"testEnvironmentOptions.url"')}. Please update your configuration.`, timers: _options => ` Option ${_chalk().default.bold('"timers"')} was replaced by ${_chalk().default.bold('"fakeTimers"')}. Please update your configuration.` }; var _default = exports["default"] = deprecatedOptions; /***/ }), /***/ "./src/Descriptions.ts": /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; /** * 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. */ const descriptions = { automock: 'All imported modules in your tests should be mocked automatically', bail: 'Stop running tests after `n` failures', cacheDirectory: 'The directory where Jest should store its cached dependency information', clearMocks: 'Automatically clear mock calls, instances, contexts and results before every test', collectCoverage: 'Indicates whether the coverage information should be collected while executing the test', collectCoverageFrom: 'An array of glob patterns indicating a set of files for which coverage information should be collected', coverageDirectory: 'The directory where Jest should output its coverage files', coveragePathIgnorePatterns: 'An array of regexp pattern strings used to skip coverage collection', coverageProvider: 'Indicates which provider should be used to instrument code for coverage', coverageReporters: 'A list of reporter names that Jest uses when writing coverage reports', coverageThreshold: 'An object that configures minimum threshold enforcement for coverage results', dependencyExtractor: 'A path to a custom dependency extractor', errorOnDeprecated: 'Make calling deprecated APIs throw helpful error messages', fakeTimers: 'The default configuration for fake timers', forceCoverageMatch: 'Force coverage collection from ignored files using an array of glob patterns', globalSetup: 'A path to a module which exports an async function that is triggered once before all test suites', globalTeardown: 'A path to a module which exports an async function that is triggered once after all test suites', globals: 'A set of global variables that need to be available in all test environments', maxWorkers: 'The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.', moduleDirectories: "An array of directory names to be searched recursively up from the requiring module's location", moduleFileExtensions: 'An array of file extensions your modules use', moduleNameMapper: 'A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module', modulePathIgnorePatterns: "An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader", notify: 'Activates notifications for test results', notifyMode: 'An enum that specifies notification mode. Requires { notify: true }', preset: "A preset that is used as a base for Jest's configuration", projects: 'Run tests from one or more projects', reporters: 'Use this configuration option to add custom reporters to Jest', resetMocks: 'Automatically reset mock state before every test', resetModules: 'Reset the module registry before running each individual test', resolver: 'A path to a custom resolver', restoreMocks: 'Automatically restore mock state and implementation before every test', rootDir: 'The root directory that Jest should scan for tests and modules within', roots: 'A list of paths to directories that Jest should use to search for files in', runner: "Allows you to use a custom runner instead of Jest's default test runner", setupFiles: 'The paths to modules that run some code to configure or set up the testing environment before each test', setupFilesAfterEnv: 'A list of paths to modules that run some code to configure or set up the testing framework before each test', slowTestThreshold: 'The number of seconds after which a test is considered as slow and reported as such in the results.', snapshotSerializers: 'A list of paths to snapshot serializer modules Jest should use for snapshot testing', testEnvironment: 'The test environment that will be used for testing', testEnvironmentOptions: 'Options that will be passed to the testEnvironment', testLocationInResults: 'Adds a location field to test results', testMatch: 'The glob patterns Jest uses to detect test files', testPathIgnorePatterns: 'An array of regexp pattern strings that are matched against all test paths, matched tests are skipped', testRegex: 'The regexp pattern or array of patterns that Jest uses to detect test files', testResultsProcessor: 'This option allows the use of a custom results processor', testRunner: 'This option allows use of a custom test runner', transform: 'A map from regular expressions to paths to transformers', transformIgnorePatterns: 'An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation', unmockedModulePathPatterns: 'An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them', verbose: 'Indicates whether each individual test should be reported during the run', watchPathIgnorePatterns: 'An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode', watchman: 'Whether to use watchman for file crawling' }; var _default = exports["default"] = descriptions; /***/ }), /***/ "./src/ReporterValidationErrors.ts": /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createArrayReporterError = createArrayReporterError; exports.createReporterError = createReporterError; exports.validateReporters = validateReporters; function _chalk() { const data = _interopRequireDefault(require("chalk")); _chalk = function () { return data; }; return data; } function _getType() { const data = require("@jest/get-type"); _getType = function () { return data; }; return data; } function _jestValidate() { const data = require("jest-validate"); _jestValidate = function () { return data; }; return data; } var _utils = __webpack_require__("./src/utils.ts"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } /** * 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. */ const validReporterTypes = ['array', 'string']; const ERROR = `${_utils.BULLET}Reporter Validation Error`; /** * Reporter Validation Error is thrown if the given arguments * within the reporter are not valid. * * This is a highly specific reporter error and in the future will be * merged with jest-validate. Till then, we can make use of it. It works * and that's what counts most at this time. */ function createReporterError(reporterIndex, reporterValue) { const errorMessage = ` Reporter at index ${reporterIndex} must be of type:\n` + ` ${_chalk().default.bold.green(validReporterTypes.join(' or '))}\n` + ' but instead received:\n' + ` ${_chalk().default.bold.red((0, _getType().getType)(reporterValue))}`; return new (_jestValidate().ValidationError)(ERROR, errorMessage, _utils.DOCUMENTATION_NOTE); } function createArrayReporterError(arrayReporter, reporterIndex, valueIndex, value, expectedType, valueName) { const errorMessage = ` Unexpected value for ${valueName} ` + `at index ${valueIndex} of reporter at index ${reporterIndex}\n` + ' Expected:\n' + ` ${_chalk().default.bold.red(expectedType)}\n` + ' Got:\n' + ` ${_chalk().default.bold.green((0, _getType().getType)(value))}\n` + ' Reporter configuration:\n' + ` ${_chalk().default.bold.green(JSON.stringify(arrayReporter, null, 2).split('\n').join('\n '))}`; return new (_jestValidate().ValidationError)(ERROR, errorMessage, _utils.DOCUMENTATION_NOTE); } function validateReporters(reporterConfig) { return reporterConfig.every((reporter, index) => { if (Array.isArray(reporter)) { validateArrayReporter(reporter, index); } else if (typeof reporter !== 'string') { throw createReporterError(index, reporter); } return true; }); } function validateArrayReporter(arrayReporter, reporterIndex) { const [path, options] = arrayReporter; if (typeof path !== 'string') { throw createArrayReporterError(arrayReporter, reporterIndex, 0, path, 'string', 'Path'); } else if (typeof options !== 'object') { throw createArrayReporterError(arrayReporter, reporterIndex, 1, options, 'object', 'Reporter Configuration'); } } /***/ }), /***/ "./src/ValidConfig.ts": /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.initialProjectOptions = exports.initialOptions = void 0; function _jestRegexUtil() { const data = require("jest-regex-util"); _jestRegexUtil = function () { return data; }; return data; } function _jestValidate() { const data = require("jest-validate"); _jestValidate = function () { return data; }; return data; } function _prettyFormat() { const data = require("pretty-format"); _prettyFormat = function () { return data; }; return data; } var _constants = __webpack_require__("./src/constants.ts"); /** * 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. */ const NODE_MODULES_REGEXP = (0, _jestRegexUtil().replacePathSepForRegex)(_constants.NODE_MODULES); const initialOptions = exports.initialOptions = { automock: false, bail: (0, _jestValidate().multipleValidOptions)(false, 0), cache: true, cacheDirectory: '/tmp/user/jest', changedFilesWithAncestor: false, changedSince: 'master', ci: false, clearMocks: false, collectCoverage: true, collectCoverageFrom: ['src', '!public'], coverageDirectory: 'coverage', coveragePathIgnorePatterns: [NODE_MODULES_REGEXP], coverageProvider: 'v8', coverageReporters: ['json', 'text', 'lcov', 'clover'], coverageThreshold: { global: { branches: 50, functions: 100, lines: 100, statements: 100 } }, dependencyExtractor: '<rootDir>/dependencyExtractor.js', detectLeaks: false, detectOpenHandles: false, displayName: (0, _jestValidate().multipleValidOptions)('test-config', { color: 'blue', name: 'test-config' }), errorOnDeprecated: false, expand: false, extensionsToTreatAsEsm: [], fakeTimers: { advanceTimers: (0, _jestValidate().multipleValidOptions)(40, true), doNotFake: ['Date', 'hrtime', 'nextTick', 'performance', 'queueMicrotask', 'requestAnimationFrame', 'cancelAnimationFrame', 'requestIdleCallback', 'cancelIdleCallback', 'setImmediate', 'clearImmediate', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'], enableGlobally: true, legacyFakeTimers: false, now: 1_483_228_800_000, timerLimit: 1000 }, filter: '<rootDir>/filter.js', forceCoverageMatch: ['**/*.t.js'], forceExit: false, globalSetup: 'setup.js', globalTeardown: 'teardown.js', globals: { __DEV__: true }, haste: { computeSha1: true, defaultPlatform: 'ios', enableSymlinks: false, forceNodeFilesystemAPI: true, hasteImplModulePath: '<rootDir>/haste_impl.js', hasteMapModulePath: '', platforms: ['ios', 'android'], retainAllFiles: false, throwOnModuleCollision: false }, id: 'string', injectGlobals: true, json: false, lastCommit: false, listTests: false, logHeapUsage: true, maxConcurrency: 5, maxWorkers: '50%', moduleDirectories: ['node_modules'], moduleFileExtensions: ['js', 'mjs', 'cjs', 'json', 'jsx', 'ts', 'mts', 'cts', 'tsx', 'node'], moduleNameMapper: { '^React$': '<rootDir>/node_modules/react' }, modulePathIgnorePatterns: ['<rootDir>/build/'], modulePaths: ['/shared/vendor/modules'], noStackTrace: false, notify: false, notifyMode: 'failure-change', onlyChanged: false, onlyFailures: false, openHandlesTimeout: 1000, passWithNoTests: false, preset: 'react-native', prettierPath: '<rootDir>/node_modules/prettier', projects: ['project-a', 'project-b/'], randomize: false, reporters: ['default', 'custom-reporter-1', ['custom-reporter-2', { configValue: true }]], resetMocks: false, resetModules: false, resolver: '<rootDir>/resolver.js', restoreMocks: false, rootDir: '/', roots: ['<rootDir>'], runTestsByPath: false, runner: 'jest-runner', runtime: '<rootDir>', sandboxInjectedGlobals: [], setupFiles: ['<rootDir>/setup.js'], setupFilesAfterEnv: ['<rootDir>/testSetupFile.js'], showSeed: false, silent: true, skipFilter: false, skipNodeResolution: false, slowTestThreshold: 5, snapshotFormat: _prettyFormat().DEFAULT_OPTIONS, snapshotResolver: '<rootDir>/snapshotResolver.js', snapshotSerializers: ['my-serializer-module'], testEnvironment: 'jest-environment-node', testEnvironmentOptions: { url: 'http://localhost', userAgent: 'Agent/007' }, testFailureExitCode: 1, testLocationInResults: false, testMatch: ['**/__tests__/**/*.?([mc])[jt]s?(x)', '**/?(*.)+(spec|test).?([mc])[jt]s?(x)'], testNamePattern: 'test signature', testPathIgnorePatterns: [NODE_MODULES_REGEXP], testRegex: (0, _jestValidate().multipleValidOptions)('(/__tests__/.*|(\\.|/)(test|spec))\\.[mc]?[jt]sx?$', ['/__tests__/\\.test\\.[mc]?[jt]sx?$', '/__tests__/\\.spec\\.[mc]?[jt]sx?$']), testResultsProcessor: 'processor-node-module', testRunner: 'circus', testSequencer: '@jest/test-sequencer', testTimeout: 5000, transform: { '\\.js$': '<rootDir>/preprocessor.js' }, transformIgnorePatterns: [NODE_MODULES_REGEXP], unmockedModulePathPatterns: ['mock'], updateSnapshot: true, useStderr: false, verbose: false, waitForUnhandledRejections: false, watch: false, watchAll: false, watchPathIgnorePatterns: ['<rootDir>/e2e/'], watchPlugins: ['path/to/yourWatchPlugin', ['jest-watch-typeahead/filename', { key: 'k', prompt: 'do something with my custom prompt' }]], watchman: true, workerIdleMemoryLimit: (0, _jestValidate().multipleValidOptions)(0.2, '50%'), workerThreads: true }; const initialProjectOptions = exports.initialProjectOptions = { automock: false, cache: true, cacheDirectory: '/tmp/user/jest', clearMocks: false, collectCoverageFrom: ['src', '!public'], coverageDirectory: 'coverage', coveragePathIgnorePatterns: [NODE_MODULES_REGEXP], coverageReporters: ['json', 'text', 'lcov', 'clover'], dependencyExtractor: '<rootDir>/dependencyExtractor.js', detectLeaks: false, detectOpenHandles: false, displayName: (0, _jestValidate().multipleValidOptions)('test-config', { color: 'blue', name: 'test-config' }), errorOnDeprecated: false, extensionsToTreatAsEsm: [], fakeTimers: { advanceTimers: (0, _jestValidate().multipleValidOptions)(40, true), doNotFake: ['Date', 'hrtime', 'nextTick', 'performance', 'queueMicrotask', 'requestAnimationFrame', 'cancelAnimationFrame', 'requestIdleCallback', 'cancelIdleCallback', 'setImmediate', 'clearImmediate', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'], enableGlobally: true, legacyFakeTimers: false, now: 1_483_228_800_000, timerLimit: 1000 }, filter: '<rootDir>/filter.js', forceCoverageMatch: ['**/*.t.js'], globalSetup: 'setup.js', globalTeardown: 'teardown.js', globals: { __DEV__: true }, haste: { computeSha1: true, defaultPlatform: 'ios', enableSymlinks: false, forceNodeFilesystemAPI: true, hasteImplModulePath: '<rootDir>/haste_impl.js', hasteMapModulePath: '', platforms: ['ios', 'android'], retainAllFiles: false, throwOnModuleCollision: false }, id: 'string', injectGlobals: true, moduleDirectories: ['node_modules'], moduleFileExtensions: ['js', 'mjs', 'cjs', 'json', 'jsx', 'ts', 'mts', 'cts', 'tsx', 'node'], moduleNameMapper: { '^React$': '<rootDir>/node_modules/react' }, modulePathIgnorePatterns: ['<rootDir>/build/'], modulePaths: ['/shared/vendor/modules'], openHandlesTimeout: 1000, preset: 'react-native', prettierPath: '<rootDir>/node_modules/prettier', reporters: ['default', 'custom-reporter-1', ['custom-reporter-2', { configValue: true }]], resetMocks: false, resetModules: false, resolver: '<rootDir>/resolver.js', restoreMocks: false, rootDir: '/', roots: ['<rootDir>'], runner: 'jest-runner', runtime: '<rootDir>', sandboxInjectedGlobals: [], setupFiles: ['<rootDir>/setup.js'], setupFilesAfterEnv: ['<rootDir>/testSetupFile.js'], skipFilter: false, skipNodeResolution: false, slowTestThreshold: 5, snapshotFormat: _prettyFormat().DEFAULT_OPTIONS, snapshotResolver: '<rootDir>/snapshotResolver.js', snapshotSerializers: ['my-serializer-module'], testEnvironment: 'jest-environment-node', testEnvironmentOptions: { url: 'http://localhost', userAgent: 'Agent/007' }, testLocationInResults: false, testMatch: ['**/__tests__/**/*.?([mc])[jt]s?(x)', '**/?(*.)+(spec|test).?([mc])[jt]s?(x)'], testPathIgnorePatterns: [NODE_MODULES_REGEXP], testRegex: (0, _jestValidate().multipleValidOptions)('(/__tests__/.*|(\\.|/)(test|spec))\\.[mc]?[jt]sx?$', ['/__tests__/\\.test\\.[mc]?[jt]sx?$', '/__tests__/\\.spec\\.[mc]?[jt]sx?$']), testRunner: 'circus', testTimeout: 5000, transform: { '\\.js$': '<rootDir>/preprocessor.js' }, transformIgnorePatterns: [NODE_MODULES_REGEXP], unmockedModulePathPatterns: ['mock'], waitForUnhandledRejections: false, watchPathIgnorePatterns: ['<rootDir>/e2e/'], workerIdleMemoryLimit: (0, _jestValidate().multipleValidOptions)(0.2, '50%') }; /***/ }), /***/ "./src/color.ts": /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDisplayNameColor = void 0; function _crypto() { const data = require("crypto"); _crypto = function () { return data; }; return data; } /** * 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. */ const colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']; const getDisplayNameColor = seed => { if (seed === undefined) { return 'white'; } const hash = (0, _crypto().createHash)('sha256'); hash.update(seed); const num = hash.digest().readUInt32LE(0); return colors[num % colors.length]; }; exports.getDisplayNameColor = getDisplayNameColor; /***/ }), /***/ "./src/constants.ts": /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PACKAGE_JSON = exports.NODE_MODULES = exports.JEST_CONFIG_EXT_TS = exports.JEST_CONFIG_EXT_ORDER = exports.JEST_CONFIG_EXT_MJS = exports.JEST_CONFIG_EXT_JSON = exports.JEST_CONFIG_EXT_JS = exports.JEST_CONFIG_EXT_CTS = exports.JEST_CONFIG_EXT_CJS = exports.JEST_CONFIG_BASE_NAME = exports.DEFAULT_JS_PATTERN = void 0; function path() { const data = _interopRequireWildcard(require("path")); path = function () { return data; }; return data; } function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } /** * 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. */ const NODE_MODULES = exports.NODE_MODULES = `${path().sep}node_modules${path().sep}`; const DEFAULT_JS_PATTERN = exports.DEFAULT_JS_PATTERN = '\\.[jt]sx?$'; const PACKAGE_JSON = exports.PACKAGE_JSON = 'package.json'; const JEST_CONFIG_BASE_NAME = exports.JEST_CONFIG_BASE_NAME = 'jest.config'; const JEST_CONFIG_EXT_CJS = exports.JEST_CONFIG_EXT_CJS = '.cjs'; const JEST_CONFIG_EXT_MJS = exports.JEST_CONFIG_EXT_MJS = '.mjs'; const JEST_CONFIG_EXT_JS = exports.JEST_CONFIG_EXT_JS = '.js'; const JEST_CONFIG_EXT_TS = exports.JEST_CONFIG_EXT_TS = '.ts'; const JEST_CONFIG_EXT_CTS = exports.JEST_CONFIG_EXT_CTS = '.cts'; const JEST_CONFIG_EXT_JSON = exports.JEST_CONFIG_EXT_JSON = '.json'; const JEST_CONFIG_EXT_ORDER = exports.JEST_CONFIG_EXT_ORDER = Object.freeze([JEST_CONFIG_EXT_JS, JEST_CONFIG_EXT_TS, JEST_CONFIG_EXT_MJS, JEST_CONFIG_EXT_CJS, JEST_CONFIG_EXT_CTS, JEST_CONFIG_EXT_JSON]); /***/ }), /***/ "./src/getCacheDirectory.ts": /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; function _os() { const data = require("os"); _os = function () { return data; }; return data; } function path() { const data = _interopRequireWildcard(require("path")); path = function () { return data; }; return data; } function _jestUtil() { const data = require("jest-util"); _jestUtil = function () { return data; }; return data; } function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } /** * 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. */ const getCacheDirectory = () => { const { getuid } = process; const tmpdirPath = path().join((0, _jestUtil().tryRealpath)((0, _os().tmpdir)()), 'jest'); if (getuid == null) { return tmpdirPath; } else { // On some platforms tmpdir() is `/tmp`, causing conflicts between different // users and permission issues. Adding an additional subdivision by UID can // help. return `${tmpdirPath}_${getuid.call(process).toString(36)}`; } }; var _default = exports["default"] = getCacheDirectory; /***/ }), /***/ "./src/getMaxWorkers.ts": /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = getMaxWorkers; function _os() { const data = require("os"); _os = function () { return data; }; return data; } /** * 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. */ function getMaxWorkers(argv, defaultOptions) { if (argv.runInBand) { return 1; } else if (argv.maxWorkers) { return parseWorkers(argv.maxWorkers); } else if (defaultOptions && defaultOptions.maxWorkers) { return parseWorkers(defaultOptions.maxWorkers); } else { // In watch mode, Jest should be unobtrusive and not use all available CPUs. const numCpus = (0, _os().availableParallelism)(); const isWatchModeEnabled = argv.watch || argv.watchAll; return Math.max(isWatchModeEnabled ? Math.floor(numCpus / 2) : numCpus - 1, 1); } } const parseWorkers = maxWorkers => { const parsed = Number.parseInt(maxWorkers.toString(), 10); if (typeof maxWorkers === 'string' && maxWorkers.trim().endsWith('%') && parsed > 0 && parsed <= 100) { const numCpus = (0, _os().availableParallelism)(); const workers = Math.floor(parsed / 100 * numCpus); return Math.max(workers, 1); } return parsed > 0 ? parsed : 1; }; /***/ }), /***/ "./src/index.ts": /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.constants = void 0; Object.defineProperty(exports, "defaults", ({ enumerable: true, get: function () { return _Defaults.default; } })); Object.defineProperty(exports, "deprecationEntries", ({ enumerable: true, get: function () { return _Deprecated.default; } })); Object.defineProperty(exports, "descriptions", ({ enumerable: true, get: function () { return _Descriptions.default; } })); Object.defineProperty(exports, "isJSONString", ({ enumerable: true, get: function () { return _utils.isJSONString; } })); Object.defineProperty(exports, "normalize", ({ enumerable: true, get: function () { return _normalize.default; } })); exports.readConfig = readConfig; exports.readConfigs = readConfigs; exports.readInitialOptions = readInitialOptions; Object.defineProperty(exports, "replaceRootDirInPath", ({ enumerable: true, get: function () { return _utils.replaceRootDirInPath; } })); 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 fs() { const data = _interopRequireWildcard(require("graceful-fs")); fs = function () { return data; }; return data; } function _jestUtil() { const data = require("jest-util"); _jestUtil = function () { return data; }; return data; } var constants = _interopRequireWildcard(__webpack_require__("./src/constants.ts")); exports.constants = constants; var _normalize = _interopRequireDefault(__webpack_require__("./src/normalize.ts")); var _readConfigFileAndSetRootDir = _interopRequireDefault(__webpack_require__("./src/readConfigFileAndSetRootDir.ts")); var _resolveConfigPath = _interopRequireDefault(__webpack_require__("./src/resolveConfigPath.ts")); var _utils = __webpack_require__("./src/utils.ts"); var _Deprecated = _interopRequireDefault(__webpack_require__("./src/Deprecated.ts")); var _Defaults = _interopRequireDefault(__webpack_require__("./src/Defaults.ts")); var _Descriptions = _interopRequireDefault(__webpack_require__("./src/Descriptions.ts")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } /** * 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. */ async function readConfig(argv, packageRootOrConfig, // Whether it needs to look into `--config` arg passed to CLI. // It only used to read initial config. If the initial config contains // `project` property, we don't want to read `--config` value and rather // read individual configs for every project. skipArgvConfigOption, parentConfigDirname, projectIndex = Number.POSITIVE_INFINITY, skipMultipleConfigError = false) { const { config: initialOptions, configPath } = await readInitialOptions(argv.config, { packageRootOrConfig, parentConfigDirname, readFromCwd: skipArgvConfigOption, skipMultipleConfigError }); const packageRoot = typeof packageRootOrConfig === 'string' ? path().resolve(packageRootOrConfig) : undefined; const { options, hasDeprecationWarnings } = await (0, _normalize.default)(initialOptions, argv, configPath, projectIndex, skipArgvConfigOption && !(packageRoot === parentConfigDirname)); const { globalConfig, projectConfig } = groupOptions(options); return { configPath, globalConfig, hasDeprecationWarnings, projectConfig }; } const groupOptions = options => ({ globalConfig: Object.freeze({ bail: options.bail, changedFilesWithAncestor: options.changedFilesWithAncestor, changedSince: options.changedSince, ci: options.ci, collectCoverage: options.collectCoverage, collectCoverageFrom: options.collectCoverageFrom, coverageDirectory: options.coverageDirectory, coverageProvider: options.coverageProvider, coverageReporters: options.coverageReporters, coverageThreshold: options.coverageThreshold, detectLeaks: options.detectLeaks, detectOpenHandles: options.detectOpenHandles, errorOnDeprecated: options.errorOnDeprecated, expand: options.expand, filter: options.filter, findRelatedTests: options.findRelatedTests, forceExit: options.forceExit, globalSetup: options.globalSetup, globalTeardown: options.globalTeardown, json: options.json, lastCommit: options.lastCommit, listTests: options.listTests, logHeapUsage: options.logHeapUsage, maxConcurrency: options.maxConcurrency, maxWorkers: options.maxWorkers, noSCM: undefined, noStackTrace: options.noStackTrace, nonFlagArgs: options.nonFlagArgs, notify: options.notify, notifyMode: options.notifyMode, onlyChanged: options.onlyChanged, onlyFailures: options.onlyFailures, openHandlesTimeout: options.openHandlesTimeout, outputFile: options.outputFile, passWithNoTests: options.passWithNoTests, projects: options.projects, randomize: options.randomize, replname: options.replname, reporters: options.reporters, rootDir: options.rootDir, runInBand: options.runInBand, runTestsByPath: options.runTestsByPath, seed: options.seed, shard: options.shard, showSeed: options.showSeed, silent: options.silent, skipFilter: options.skipFilter, snapshotFormat: options.snapshotFormat, testFailureExitCode: options.testFailureExitCode, testNamePattern: options.testNamePattern, testPathPatterns: options.testPathPatterns, testResultsProcessor: options.testResultsProcessor, testSequencer: options.testSequencer, testTimeout: options.testTimeout, updateSnapshot: options.updateSnapshot, useStderr: options.useStderr, verbose: options.verbose, waitForUnhandledRejections: options.waitForUnhandledRejections, watch: options.watch, watchAll: options.watchAll, watchPlugins: options.watchPlugins, watchman: options.watchman, workerIdleMemoryLimit: options.workerIdleMemoryLimit, workerThreads: options.workerThreads }), projectConfig: Object.freeze({ automock: options.automock, cache: options.cache, cacheDirectory: options.cacheDirectory, clearMocks: options.clearMocks, collectCoverageFrom: options.collectCoverageFrom, coverageDirectory: options.coverageDirectory, coveragePathIgnorePatterns: options.coveragePathIgnorePatterns, coverageReporters: options.coverageReporters, cwd: options.cwd, dependencyExtractor: options.dependencyExtractor, detectLeaks: options.detectLeaks, detectOpenHandles: options.detectOpenHandles, displayName: options.displayName, errorOnDeprecated: options.errorOnDeprecated, extensionsToTreatAsEsm: options.extensionsToTreatAsEsm, fakeTimers: options.fakeTimers, filter: options.filter, forceCoverageMatch: options.forceCoverageMatch, globalSetup: options.globalSetup, globalTeardown: options.globalTeardown, globals: options.globals, haste: options.haste, id: options.id, injectGlobals: options.injectGlobals, moduleDirectories: options.moduleDirectories, moduleFileExtensions: options.moduleFileExtensions, moduleNameMapper: options.moduleNameMapper, modulePathIgnorePatterns: options.modulePathIgnorePatterns, modulePaths: options.modulePaths, openHandlesTimeout: options.openHandlesTimeout, prettierPath: options.prettierPath, reporters: options.reporters, resetMocks: options.resetMocks, resetModules: options.resetModules, resolver: options.resolver, restoreMocks: options.restoreMocks, rootDir: options.rootDir, roots: options.roots, runner: options.runner, runtime: options.runtime, sandboxInjectedGlobals: options.sandboxInjectedGlobals, setupFiles: options.setupFiles, setupFilesAfterEnv: options.setupFilesAfterEnv, skipFilter: options.skipFilter, skipNodeResolution: options.skipNodeResolution, slowTestThreshold: options.slowTestThreshold, snapshotFormat: options.snapshotFormat, snapshotResolver: options.snapshotResolver, snapshotSerializers: options.snapshotSerializers, testEnvironment: options.testEnvironment, testEnvironmentOptions: options.testEnvironmentOptions, testLocationInResults: options.testLocationInResults, testMatch: options.testMatch, testPathIgnorePatterns: options.testPathIgnorePatterns, testRegex: options.testRegex, testRunner: options.testRunner, testTimeout: options.testTimeout, transform: options.transform, transformIgnorePatterns: options.transformIgnorePatterns, unmockedModulePathPatterns: options.unmockedModulePathPatterns, waitForUnhandledRejections: options.waitForUnhandledRejections, watchPathIgnorePatterns: options.watchPathIgnorePatterns }) }); const ensureNoDuplicateConfigs = (parsedConfigs, projects) => { if (projects.length <= 1) { return; } const configPathMap = new Map(); for (const config of parsedConfigs) { const { configPath } = config; if (configPathMap.has(configPath)) { const message = `Whoops! Two projects resolved to the same config path: ${_chalk().default.bold(String(configPath))}: Project 1: ${_chalk().default.bold(projects[parsedConfigs.indexOf(config)])} Project 2: ${_chalk().default.bold(projects[parsedConfigs.indexOf(configPathMap.get(configPath))])} This usually means that your ${_chalk().default.bold('"projects"')} config includes a directory that doesn't have any configuration recognizable by Jest. Please fix it. `; throw new Error(message); } if (configPath !== null) { configPathMap.set(configPath, config); } } }; /** * Reads the jest config, without validating them or filling it out with defaults. * @param config The path to the file or serialized config. * @param param1 Additional options * @returns The raw initial config (not validated) */ async function readInitialOptions(config, { packageRootOrConfig = process.cwd(), parentConfigDirname = null, readFromCwd = false, skipMultipleConfigError = false } = {}) { if (typeof packageRootOrConfig !== 'string') { if (parentConfigDirname) { const rawOptions = packageRootOrConfig; rawOptions.rootDir = rawOptions.rootDir ? (0, _utils.replaceRootDirInPath)(parentConfigDirname, rawOptions.rootDir) : parentConfigDirname; return { config: rawOptions, configPath: null }; } else { throw new Error('Jest: Cannot use configuration as an object without a file path.'); } } if ((0, _utils.isJSONString)(config)) { try { // A JSON string was passed to `--config` argument and we can parse it // and use as is. const initialOptions = JSON.parse(config); // NOTE: we might need to resolve this dir to an absolute path in the future initialOptions.rootDir = initialOptions.rootDir || packageRootOrConfig; return { config: initialOptions, configPath: null }; } catch { throw new Error('There was an error while parsing the `--config` argument as a JSON string.'); } } if (!readFromCwd && typeof config == 'string') { // A string passed to `--config`, which is either a direct path to the config // or a path to directory containing `package.json`, `jest.config.js` or `jest.config.ts` const configPath = (0, _resolveConfigPath.default)(config, process.cwd(), skipMultipleConfigError); return { config: await (0, _readConfigFileAndSetRootDir.default)(configPath), configPath }; } // Otherwise just try to find config in the current rootDir. const configPath = (0, _resolveConfigPath.default)(packageRootOrConfig, process.cwd(), skipMultipleConfigError); return { config: await (0, _readConfigFileAndSetRootDir.default)(configPath), configPath }; } // Possible scenarios: // 1. jest --config config.json // 2. jest --projects p1 p2 // 3. jest --projects p1 p2 --config config.json // 4. jest --projects p1 // 5. jest // // If no projects are specified, process.cwd() will be used as the default // (and only) project. async function readConfigs(argv, projectPaths) { let globalConfig; let hasDeprecationWarnings; let configs = []; let projects = projectPaths; let configPath; if (projectPaths.length === 1) { const parsedConfig = await readConfig(argv, projects[0]); configPath = parsedConfig.configPath; hasDeprecationWarnings = parsedConfig.hasDeprecationWarnings; globalConfig = parsedConfig.globalConfig; configs = [parsedConfig.projectConfig]; if (globalConfig.projects && globalConfig.projects.length > 0) { // Even though we had one project in CLI args, there might be more // projects defined in the config. // In other words, if this was a single project, // and its config has `projects` settings, use that value instead. projects = globalConfig.projects; } } if (projects.length > 0) { const cwd = process.platform === 'win32' ? (0, _jestUtil().tryRealpath)(process.cwd()) : process.cwd(); const projectIsCwd = projects[0] === cwd; const parsedConfigs = await Promise.all(projects.filter(root => { // Ignore globbed files that cannot be `require`d. if (typeof root === 'string' && fs().existsSync(root) && !fs().lstatSync(root).isDirectory() && !constants.JEST_CONFIG_EXT_ORDER.some(ext => root.endsWith(ext))) { return false; } return true; }).map((root, projectIndex) => { const projectIsTheOnlyProject = projectIndex === 0 && projects.length === 1; const skipArgvConfigOption = !(projectIsTheOnlyProject && projectIsCwd); return readConfig(argv, root, skipArgvConfigOption, configPath ? path().dirname(configPath) : cwd, projectIndex, // we wanna skip the warning if this is the "main" project projectIsCwd); })); ensureNoDuplicateConfigs(parsedConfigs, projects); configs = parsedConfigs.map(({ projectConfig }) => projectConfig); if (!hasDeprecationWarnings) { hasDeprecationWarnings = parsedConfigs.some(({ hasDeprecationWarnings }) => !!hasDeprecationWarnings); } // If no config was passed initially, use the one from the first project if (!globalConfig) { globalConfig = parsedConfigs[0].globalConfig; } } if (!globalConfig || configs.length === 0) { throw new Error('jest: No configuration found for any project.'); } return { configs, globalConfig, hasDeprecationWarnings: !!hasDeprecationWarnings }; } /***/ }), /***/ "./src/normalize.ts": /***/ ((module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = normalize; function _crypto() { const data = require("crypto"); _crypto = function () { return data; }; return data; } function _os() { const data = require("os"); _os = 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 _pattern() { const data = require("@jest/pattern"); _pattern = 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(__webpack_require__("./src/Defaults.ts")); var _Deprecated = _interopRequireDefault(__webpack_require__("./src/Deprecated.ts")); var _ReporterValidationErrors = __webpack_require__("./src/ReporterValidationErrors.ts"); var _ValidConfig = __webpack_require__("./src/ValidConfig.ts"); var _color = __webpack_require__("./src/color.ts"); var _constants = __webpack_require__("./src/constants.ts"); var _getMaxWorkers = _interopRequireDefault(__webpack_require__("./src/getMaxWorkers.ts")); var _parseShardPair = __webpack_require__("./src/parseShardPair.ts"); var _setFromArgv = _interopRequireDefault(__webpack_require__("./src/setFromArgv.ts")); var _stringToBytes = _interopRequireDefault(__webpack_require__("./src/stringToBytes.ts")); var _utils = __webpack_require__("./src/utils.ts"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } functio