From 619e01d045e3d401d1d2986c6b7cbfef8f9a40b1 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Sun, 17 Nov 2019 21:10:29 +0100 Subject: [PATCH 1/2] fix(jest-types): tighten Config types and set more defaults --- CHANGELOG.md | 1 + packages/jest-config/src/Defaults.ts | 14 -- packages/jest-config/src/normalize.ts | 45 +++++- packages/jest-haste-map/src/index.ts | 6 +- packages/jest-haste-map/src/types.ts | 2 +- .../jest-reporters/src/coverage_reporter.ts | 19 ++- packages/jest-resolve/src/types.ts | 2 +- packages/jest-runtime/src/cli/index.ts | 3 +- packages/jest-runtime/src/index.ts | 7 +- .../jest-transform/src/ScriptTransformer.ts | 2 +- packages/jest-types/src/Config.ts | 133 +++++++----------- 11 files changed, 112 insertions(+), 122 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46632517999e..dd6504377a56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,7 @@ - `[jest-snapshot]` [**BREAKING**] Remove `report` method and throw matcher errors ([#9049](https://github.com/facebook/jest/pull/9049)) - `[jest-transform]` Properly cache transformed files across tests ([#8890](https://github.com/facebook/jest/pull/8890)) - `[jest-transform]` Don't fail the test suite when a generated source map is invalid ([#9058](https://github.com/facebook/jest/pull/9058)) +- `[jest-types]` [**BREAKING**] Use less `null | undefined` in config types ([#9200](https://github.com/facebook/jest/pull/9200)) - `[jest-utils]` Allow querying process.domain ([#9136](https://github.com/facebook/jest/pull/9136)) - `[pretty-format]` Correctly detect memoized elements ([#9196](https://github.com/facebook/jest/pull/9196)) diff --git a/packages/jest-config/src/Defaults.ts b/packages/jest-config/src/Defaults.ts index 26c40f2f912f..e096029b7795 100644 --- a/packages/jest-config/src/Defaults.ts +++ b/packages/jest-config/src/Defaults.ts @@ -21,18 +21,11 @@ const defaultOptions: Config.DefaultOptions = { changedFilesWithAncestor: false, clearMocks: false, collectCoverage: false, - collectCoverageFrom: null, - coverageDirectory: null, coveragePathIgnorePatterns: [NODE_MODULES_REGEXP], coverageReporters: ['json', 'text', 'lcov', 'clover'], - coverageThreshold: null, - dependencyExtractor: null, errorOnDeprecated: false, expand: false, - filter: null, forceCoverageMatch: [], - globalSetup: null, - globalTeardown: null, globals: {}, haste: { computeSha1: false, @@ -48,14 +41,10 @@ const defaultOptions: Config.DefaultOptions = { noStackTrace: false, notify: false, notifyMode: 'failure-change', - preset: null, prettierPath: 'prettier', - projects: null, resetMocks: false, resetModules: false, - resolver: null, restoreMocks: false, - rootDir: null, roots: [''], runTestsByPath: false, runner: 'jest-runner', @@ -70,15 +59,12 @@ const defaultOptions: Config.DefaultOptions = { testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[tj]s?(x)'], testPathIgnorePatterns: [NODE_MODULES_REGEXP], testRegex: [], - testResultsProcessor: null, testRunner: 'jasmine2', testSequencer: '@jest/test-sequencer', testURL: 'http://localhost', timers: 'real', - transform: null, transformIgnorePatterns: [NODE_MODULES_REGEXP], useStderr: false, - verbose: null, watch: false, watchPathIgnorePatterns: [], watchman: true, diff --git a/packages/jest-config/src/normalize.ts b/packages/jest-config/src/normalize.ts index 100b4338cc06..96111241f9d3 100644 --- a/packages/jest-config/src/normalize.ts +++ b/packages/jest-config/src/normalize.ts @@ -673,7 +673,7 @@ export default function normalize( key, rootDir: options.rootDir, }), - ...(Array.isArray(transformElement) ? [transformElement[1]] : []), + Array.isArray(transformElement) ? transformElement[1] : {}, ]; }); break; @@ -947,6 +947,29 @@ export default function normalize( newOptions.onlyChanged = newOptions.watch; } + if (!newOptions.onlyChanged) { + newOptions.onlyChanged = false; + } + + if (!newOptions.lastCommit) { + newOptions.lastCommit = false; + } + + if (!newOptions.onlyFailures) { + newOptions.onlyFailures = false; + } + + if (!newOptions.watchAll) { + newOptions.watchAll = false; + } + + // as any since it can happen. We really need to fix the types here + if ( + newOptions.moduleNameMapper === (DEFAULT_CONFIG.moduleNameMapper as any) + ) { + newOptions.moduleNameMapper = []; + } + newOptions.updateSnapshot = argv.ci && !argv.updateSnapshot ? 'none' @@ -1014,6 +1037,26 @@ export default function normalize( newOptions.collectCoverageFrom = []; } + if (!newOptions.findRelatedTests) { + newOptions.findRelatedTests = false; + } + + if (!newOptions.projects) { + newOptions.projects = []; + } + + if (!newOptions.extraGlobals) { + newOptions.extraGlobals = []; + } + + if (!newOptions.forceExit) { + newOptions.forceExit = false; + } + + if (!newOptions.logHeapUsage) { + newOptions.logHeapUsage = false; + } + return { hasDeprecationWarnings, options: newOptions, diff --git a/packages/jest-haste-map/src/index.ts b/packages/jest-haste-map/src/index.ts index 61b83f7ea904..b936e149bf55 100644 --- a/packages/jest-haste-map/src/index.ts +++ b/packages/jest-haste-map/src/index.ts @@ -54,7 +54,7 @@ type Options = { computeDependencies?: boolean; computeSha1?: boolean; console?: Console; - dependencyExtractor?: string; + dependencyExtractor?: string | null; extensions: Array; forceNodeFilesystemAPI?: boolean; hasteImplModulePath?: string; @@ -79,7 +79,7 @@ type InternalOptions = { cacheDirectory: string; computeDependencies: boolean; computeSha1: boolean; - dependencyExtractor?: string; + dependencyExtractor: string | null; extensions: Array; forceNodeFilesystemAPI: boolean; hasteImplModulePath?: string; @@ -251,7 +251,7 @@ class HasteMap extends EventEmitter { ? true : options.computeDependencies, computeSha1: options.computeSha1 || false, - dependencyExtractor: options.dependencyExtractor, + dependencyExtractor: options.dependencyExtractor || null, extensions: options.extensions, forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, hasteImplModulePath: options.hasteImplModulePath, diff --git a/packages/jest-haste-map/src/types.ts b/packages/jest-haste-map/src/types.ts index 075df3f167b2..aa1b4ee5e24e 100644 --- a/packages/jest-haste-map/src/types.ts +++ b/packages/jest-haste-map/src/types.ts @@ -16,7 +16,7 @@ export type Mapper = (item: string) => Array | null; export type WorkerMessage = { computeDependencies: boolean; computeSha1: boolean; - dependencyExtractor?: string; + dependencyExtractor?: string | null; rootDir: string; filePath: string; hasteImplModulePath?: string; diff --git a/packages/jest-reporters/src/coverage_reporter.ts b/packages/jest-reporters/src/coverage_reporter.ts index 505b04f04e41..dde9ed0a6b5d 100644 --- a/packages/jest-reporters/src/coverage_reporter.ts +++ b/packages/jest-reporters/src/coverage_reporter.ts @@ -107,7 +107,7 @@ export default class CoverageReporter extends BaseReporter { ); } - this._checkThreshold(this._globalConfig, map); + this._checkThreshold(map); } private async _addUntestedFiles( @@ -209,11 +209,10 @@ export default class CoverageReporter extends BaseReporter { } } - private _checkThreshold( - globalConfig: Config.GlobalConfig, - map: istanbulCoverage.CoverageMap, - ) { - if (globalConfig.coverageThreshold) { + private _checkThreshold(map: istanbulCoverage.CoverageMap) { + const {coverageThreshold} = this._globalConfig; + + if (coverageThreshold) { function check( name: string, thresholds: Config.CoverageThresholdValue, @@ -250,7 +249,7 @@ export default class CoverageReporter extends BaseReporter { PATH: 'path', }; const coveredFiles = map.files(); - const thresholdGroups = Object.keys(globalConfig.coverageThreshold); + const thresholdGroups = Object.keys(coverageThreshold); const groupTypeByThresholdGroup: {[index: string]: string} = {}; const filesByGlob: {[index: string]: Array} = {}; @@ -342,7 +341,7 @@ export default class CoverageReporter extends BaseReporter { errors = errors.concat( check( thresholdGroup, - globalConfig.coverageThreshold[thresholdGroup], + coverageThreshold[thresholdGroup], coverage, ), ); @@ -357,7 +356,7 @@ export default class CoverageReporter extends BaseReporter { errors = errors.concat( check( thresholdGroup, - globalConfig.coverageThreshold[thresholdGroup], + coverageThreshold[thresholdGroup], coverage, ), ); @@ -370,7 +369,7 @@ export default class CoverageReporter extends BaseReporter { errors = errors.concat( check( fileMatchingGlob, - globalConfig.coverageThreshold[thresholdGroup], + coverageThreshold[thresholdGroup], map.fileCoverageFor(fileMatchingGlob).toSummary(), ), ); diff --git a/packages/jest-resolve/src/types.ts b/packages/jest-resolve/src/types.ts index 1c65ac50af57..03b372b0cfd5 100644 --- a/packages/jest-resolve/src/types.ts +++ b/packages/jest-resolve/src/types.ts @@ -14,7 +14,7 @@ export type ResolverConfig = { hasCoreModules: boolean; moduleDirectories: Array; moduleNameMapper?: Array | null; - modulePaths: Array; + modulePaths?: Array; platforms?: Array; resolver?: Config.Path | null; rootDir: Config.Path; diff --git a/packages/jest-runtime/src/cli/index.ts b/packages/jest-runtime/src/cli/index.ts index 0c701d5a29f1..a70cf4ac3ead 100644 --- a/packages/jest-runtime/src/cli/index.ts +++ b/packages/jest-runtime/src/cli/index.ts @@ -68,10 +68,9 @@ export function run(cliArgv?: Config.Argv, cliInfo?: Array) { const options = readConfig(argv, root); const globalConfig = options.globalConfig; // Always disable automocking in scripts. - const config = { + const config: Config.ProjectConfig = { ...options.projectConfig, automock: false, - unmockedModulePathPatterns: null, }; // Break circular dependency diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index e56d5c3ca113..e6de0ba3d73e 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -123,7 +123,7 @@ class Runtime { changedFiles: undefined, collectCoverage: false, collectCoverageFrom: [], - collectCoverageOnlyFrom: null, + collectCoverageOnlyFrom: undefined, }; this._currentlyExecutingModulePath = ''; this._environment = environment; @@ -489,7 +489,7 @@ class Runtime { collectCoverage: this._coverageOptions.collectCoverage, collectCoverageFrom: this._coverageOptions.collectCoverageFrom, collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom, - extraGlobals: this._config.extraGlobals || [], + extraGlobals: this._config.extraGlobals, }; } @@ -713,7 +713,6 @@ class Runtime { Object.defineProperty(localModule, 'require', { value: this._createRequireImplementation(localModule, options), }); - const extraGlobals = this._config.extraGlobals || []; const transformedFile = this._scriptTransformer.transform( filename, this._getFullTransformationOptions(options), @@ -750,7 +749,7 @@ class Runtime { filename, localModule.require as LocalModuleRequire, ), // jest object - ...extraGlobals.map(globalVariable => { + ...this._config.extraGlobals.map(globalVariable => { if (this._environment.global[globalVariable]) { return this._environment.global[globalVariable]; } diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index e8a971aa2905..c049b27f0524 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -361,7 +361,7 @@ export default class ScriptTransformer { (this.shouldTransform(filename) || instrument); try { - const extraGlobals = (options && options.extraGlobals) || []; + const extraGlobals = options ? options.extraGlobals : []; if (willTransform) { const transformedSource = this.transformSource( diff --git a/packages/jest-types/src/Config.ts b/packages/jest-types/src/Config.ts index 3cb344ce9932..f498f8f843a3 100644 --- a/packages/jest-types/src/Config.ts +++ b/packages/jest-types/src/Config.ts @@ -15,7 +15,7 @@ export type Glob = string; export type HasteConfig = { computeSha1?: boolean; - defaultPlatform?: string | null | undefined; + defaultPlatform?: string | null; hasteImplModulePath?: string; platforms?: Array; providesModuleNodeModules: Array; @@ -36,49 +36,29 @@ export type DefaultOptions = { changedFilesWithAncestor: boolean; clearMocks: boolean; collectCoverage: boolean; - collectCoverageFrom: Array | null | undefined; - coverageDirectory: string | null | undefined; coveragePathIgnorePatterns: Array; coverageReporters: Array; - coverageThreshold: - | { - global: { - [key: string]: number; - }; - } - | null - | undefined; - dependencyExtractor: string | null | undefined; errorOnDeprecated: boolean; expand: boolean; - filter: Path | null | undefined; forceCoverageMatch: Array; globals: ConfigGlobals; - globalSetup: string | null | undefined; - globalTeardown: string | null | undefined; haste: HasteConfig; - maxWorkers: number | string; maxConcurrency: number; + maxWorkers: number | string; moduleDirectories: Array; moduleFileExtensions: Array; - moduleNameMapper: { - [key: string]: string; - }; + moduleNameMapper: Record; modulePathIgnorePatterns: Array; noStackTrace: boolean; notify: boolean; - notifyMode: string; - preset: string | null | undefined; - prettierPath: string | null | undefined; - projects: Array | null | undefined; + notifyMode: NotifyMode; + prettierPath: string; resetMocks: boolean; resetModules: boolean; - resolver: Path | null | undefined; restoreMocks: boolean; - rootDir: Path | null | undefined; - roots: Array | null | undefined; - runner: string; + roots: Array; runTestsByPath: boolean; + runner: 'jest-runner'; setupFiles: Array; setupFilesAfterEnv: Array; skipFilter: boolean; @@ -90,22 +70,14 @@ export type DefaultOptions = { testMatch: Array; testPathIgnorePatterns: Array; testRegex: Array; - testResultsProcessor: string | null | undefined; - testRunner: string | null | undefined; + testRunner: string; testSequencer: string; testURL: string; timers: 'real' | 'fake'; - transform: - | { - [regex: string]: Path | TransformerConfig; - } - | null - | undefined; transformIgnorePatterns: Array; - watchPathIgnorePatterns: Array; useStderr: boolean; - verbose: boolean | null | undefined; watch: boolean; + watchPathIgnorePatterns: Array; watchman: boolean; }; @@ -210,7 +182,7 @@ export type InitialOptions = Partial<{ testPathDirs: Array; testPathIgnorePatterns: Array; testRegex: string | Array; - testResultsProcessor: string | null | undefined; + testResultsProcessor: string; testRunner: string; testSequencer: string; testURL: string; @@ -224,7 +196,7 @@ export type InitialOptions = Partial<{ unmockedModulePathPatterns: Array; updateSnapshot: boolean; useStderr: boolean; - verbose: boolean | null | undefined; + verbose?: boolean; watch: boolean; watchAll: boolean; watchman: boolean; @@ -255,38 +227,32 @@ type CoverageThreshold = { export type GlobalConfig = { bail: number; - changedSince: string; + changedSince?: string; changedFilesWithAncestor: boolean; collectCoverage: boolean; collectCoverageFrom: Array; - collectCoverageOnlyFrom: - | { - [key: string]: boolean; - } - | null - | undefined; + collectCoverageOnlyFrom?: { + [key: string]: boolean; + }; coverageDirectory: string; coveragePathIgnorePatterns?: Array; coverageReporters: Array; - coverageThreshold: CoverageThreshold; + coverageThreshold?: CoverageThreshold; detectLeaks: boolean; detectOpenHandles: boolean; - enabledTestsMap: - | { - [key: string]: { - [key: string]: boolean; - }; - } - | null - | undefined; + enabledTestsMap?: { + [key: string]: { + [key: string]: boolean; + }; + }; expand: boolean; extraGlobals: Array; - filter: Path | null | undefined; + filter?: Path; findRelatedTests: boolean; forceExit: boolean; json: boolean; - globalSetup: string | null | undefined; - globalTeardown: string | null | undefined; + globalSetup?: string; + globalTeardown?: string; lastCommit: boolean; logHeapUsage: boolean; listTests: boolean; @@ -294,40 +260,37 @@ export type GlobalConfig = { maxWorkers: number; noStackTrace: boolean; nonFlagArgs: Array; - noSCM: boolean | null | undefined; + noSCM?: boolean; notify: boolean; notifyMode: NotifyMode; - outputFile: Path | null | undefined; + outputFile?: Path; onlyChanged: boolean; onlyFailures: boolean; passWithNoTests: boolean; projects: Array; - replname: string | null | undefined; - reporters: Array; + replname?: string; + reporters?: Array; runTestsByPath: boolean; rootDir: Path; - silent: boolean; + silent?: boolean; skipFilter: boolean; errorOnDeprecated: boolean; testFailureExitCode: number; - testNamePattern: string; + testNamePattern?: string; testPathPattern: string; - testResultsProcessor: string | null | undefined; + testResultsProcessor?: string; testSequencer: string; - testTimeout: number; + testTimeout?: number; updateSnapshot: SnapshotUpdateState; useStderr: boolean; - verbose: boolean | null | undefined; + verbose?: boolean; watch: boolean; watchAll: boolean; watchman: boolean; - watchPlugins: - | Array<{ - path: string; - config: Record; - }> - | null - | undefined; + watchPlugins?: Array<{ + path: string; + config: Record; + }> | null; }; export type ProjectConfig = { @@ -344,23 +307,23 @@ export type ProjectConfig = { displayName?: DisplayName; errorOnDeprecated: boolean; extraGlobals: Array; - filter: Path | null | undefined; + filter?: Path; forceCoverageMatch: Array; - globalSetup: string | null | undefined; - globalTeardown: string | null | undefined; + globalSetup?: string; + globalTeardown?: string; globals: ConfigGlobals; haste: HasteConfig; moduleDirectories: Array; moduleFileExtensions: Array; - moduleLoader: Path; + moduleLoader?: Path; moduleNameMapper: Array<[string, string]>; modulePathIgnorePatterns: Array; - modulePaths: Array; + modulePaths?: Array; name: string; prettierPath: string; resetMocks: boolean; resetModules: boolean; - resolver: Path | null | undefined; + resolver?: Path; restoreMocks: boolean; rootDir: Path; roots: Array; @@ -368,8 +331,8 @@ export type ProjectConfig = { setupFiles: Array; setupFilesAfterEnv: Array; skipFilter: boolean; - skipNodeResolution: boolean; - snapshotResolver: Path | null | undefined; + skipNodeResolution?: boolean; + snapshotResolver?: Path; snapshotSerializers: Array; testEnvironment: string; testEnvironmentOptions: Record; @@ -383,7 +346,7 @@ export type ProjectConfig = { transform: Array<[string, Path, Record]>; transformIgnorePatterns: Array; watchPathIgnorePatterns: Array; - unmockedModulePathPatterns: Array | null | undefined; + unmockedModulePathPatterns?: Array; }; export type Argv = Arguments< @@ -456,7 +419,7 @@ export type Argv = Arguments< testPathIgnorePatterns: Array; testPathPattern: Array; testRegex: string | Array; - testResultsProcessor: string | null | undefined; + testResultsProcessor: string; testRunner: string; testSequencer: string; testURL: string; @@ -467,7 +430,7 @@ export type Argv = Arguments< unmockedModulePathPatterns: Array | null | undefined; updateSnapshot: boolean; useStderr: boolean; - verbose: boolean | null | undefined; + verbose: boolean; version: boolean; watch: boolean; watchAll: boolean; From 794f147ff8889c26e26df2d99efd676909027bb7 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Sun, 17 Nov 2019 22:35:19 +0100 Subject: [PATCH 2/2] update snaps and make `extraGlobals` optional in `@jest/transform` --- .../moduleNameMapper.test.ts.snap | 2 +- .../__snapshots__/showConfig.test.ts.snap | 27 +++++++++---------- .../__tests__/__snapshots__/init.test.js.snap | 26 +++++++++--------- .../src/__tests__/normalize.test.js | 26 +++++++++--------- .../jest-transform/src/ScriptTransformer.ts | 3 +-- packages/jest-transform/src/types.ts | 2 +- 6 files changed, 42 insertions(+), 44 deletions(-) diff --git a/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap b/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap index ca8e5b11d543..73bf63d59f7a 100644 --- a/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap +++ b/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap @@ -19,7 +19,7 @@ FAIL __tests__/index.js "moduleNameMapper": { "/\\.(css|less)$/": "no-such-module" }, - "resolver": null + "resolver": undefined } 8 | 'use strict'; diff --git a/e2e/__tests__/__snapshots__/showConfig.test.ts.snap b/e2e/__tests__/__snapshots__/showConfig.test.ts.snap index 6e77a0ed28f2..d0ad02f0098e 100644 --- a/e2e/__tests__/__snapshots__/showConfig.test.ts.snap +++ b/e2e/__tests__/__snapshots__/showConfig.test.ts.snap @@ -13,14 +13,11 @@ exports[`--showConfig outputs config info and exits 1`] = ` "/node_modules/" ], "cwd": "<>", - "dependencyExtractor": null, "detectLeaks": false, "detectOpenHandles": false, "errorOnDeprecated": false, - "filter": null, + "extraGlobals": [], "forceCoverageMatch": [], - "globalSetup": null, - "globalTeardown": null, "globals": {}, "haste": { "computeSha1": false, @@ -38,13 +35,12 @@ exports[`--showConfig outputs config info and exits 1`] = ` "tsx", "node" ], - "moduleNameMapper": {}, + "moduleNameMapper": [], "modulePathIgnorePatterns": [], "name": "[md5 hash]", "prettierPath": "prettier", "resetMocks": false, "resetModules": false, - "resolver": null, "restoreMocks": false, "rootDir": "<>", "roots": [ @@ -72,7 +68,8 @@ exports[`--showConfig outputs config info and exits 1`] = ` "transform": [ [ "^.+\\\\.[jt]sx?$", - "<>/babel-jest/build/index.js" + "<>/babel-jest/build/index.js", + {} ] ], "transformIgnorePatterns": [ @@ -93,35 +90,37 @@ exports[`--showConfig outputs config info and exits 1`] = ` "lcov", "clover" ], - "coverageThreshold": null, "detectLeaks": false, "detectOpenHandles": false, "errorOnDeprecated": false, "expand": false, - "filter": null, - "globalSetup": null, - "globalTeardown": null, + "extraGlobals": [], + "findRelatedTests": false, + "forceExit": false, "json": false, + "lastCommit": false, "listTests": false, + "logHeapUsage": false, "maxConcurrency": 5, "maxWorkers": "[maxWorkers]", "noStackTrace": false, "nonFlagArgs": [], "notify": false, "notifyMode": "failure-change", + "onlyChanged": false, + "onlyFailures": false, "passWithNoTests": false, - "projects": null, + "projects": [], "rootDir": "<>", "runTestsByPath": false, "skipFilter": false, "testFailureExitCode": 1, "testPathPattern": "", - "testResultsProcessor": null, "testSequencer": "<>/jest-test-sequencer/build/index.js", "updateSnapshot": "all", "useStderr": false, - "verbose": null, "watch": false, + "watchAll": false, "watchman": true }, "version": "[version]" diff --git a/packages/jest-cli/src/init/__tests__/__snapshots__/init.test.js.snap b/packages/jest-cli/src/init/__tests__/__snapshots__/init.test.js.snap index 768ccc23e640..63b08ad015bb 100644 --- a/packages/jest-cli/src/init/__tests__/__snapshots__/init.test.js.snap +++ b/packages/jest-cli/src/init/__tests__/__snapshots__/init.test.js.snap @@ -42,10 +42,10 @@ module.exports = { // collectCoverage: false, // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: null, + // collectCoverageFrom: undefined, // The directory where Jest should output its coverage files - // coverageDirectory: null, + // coverageDirectory: undefined, // An array of regexp pattern strings used to skip coverage collection // coveragePathIgnorePatterns: [ @@ -61,10 +61,10 @@ module.exports = { // ], // An object that configures minimum threshold enforcement for coverage results - // coverageThreshold: null, + // coverageThreshold: undefined, // A path to a custom dependency extractor - // dependencyExtractor: null, + // dependencyExtractor: undefined, // Make calling deprecated APIs throw helpful error messages // errorOnDeprecated: false, @@ -73,10 +73,10 @@ module.exports = { // forceCoverageMatch: [], // A path to a module which exports an async function that is triggered once before all test suites - // globalSetup: null, + // globalSetup: undefined, // A path to a module which exports an async function that is triggered once after all test suites - // globalTeardown: null, + // globalTeardown: undefined, // A set of global variables that need to be available in all test environments // globals: {}, @@ -112,10 +112,10 @@ module.exports = { // notifyMode: \\"failure-change\\", // A preset that is used as a base for Jest's configuration - // preset: null, + // preset: undefined, // Run tests from one or more projects - // projects: null, + // projects: undefined, // Use this configuration option to add custom reporters to Jest // reporters: undefined, @@ -127,13 +127,13 @@ module.exports = { // resetModules: false, // A path to a custom resolver - // resolver: null, + // resolver: undefined, // Automatically restore mock state between every test // restoreMocks: false, // The root directory that Jest should scan for tests and modules within - // rootDir: null, + // rootDir: undefined, // A list of paths to directories that Jest should use to search for files in // roots: [ @@ -176,7 +176,7 @@ module.exports = { // testRegex: [], // This option allows the use of a custom results processor - // testResultsProcessor: null, + // testResultsProcessor: undefined, // This option allows use of a custom test runner // testRunner: \\"jasmine2\\", @@ -188,7 +188,7 @@ module.exports = { // timers: \\"real\\", // A map from regular expressions to paths to transformers - // transform: null, + // transform: undefined, // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation // transformIgnorePatterns: [ @@ -199,7 +199,7 @@ module.exports = { // unmockedModulePathPatterns: undefined, // Indicates whether each individual test should be reported during the run - // verbose: null, + // verbose: undefined, // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode // watchPathIgnorePatterns: [], diff --git a/packages/jest-config/src/__tests__/normalize.test.js b/packages/jest-config/src/__tests__/normalize.test.js index 6820fc169e20..8bf1a94417de 100644 --- a/packages/jest-config/src/__tests__/normalize.test.js +++ b/packages/jest-config/src/__tests__/normalize.test.js @@ -328,12 +328,12 @@ describe('transform', () => { ); expect(options.transform).toEqual([ - [DEFAULT_CSS_PATTERN, '/root/node_modules/jest-regex-util'], - [DEFAULT_JS_PATTERN, require.resolve('babel-jest')], - ['abs-path', '/qux/quux'], + [DEFAULT_CSS_PATTERN, '/root/node_modules/jest-regex-util', {}], + [DEFAULT_JS_PATTERN, require.resolve('babel-jest'), {}], + ['abs-path', '/qux/quux', {}], ]); }); - it("pulls in config if it's passed as an array", () => { + it("pulls in config if it's passed as an array, and defaults to empty object", () => { const {options} = normalize( { rootDir: '/root/', @@ -346,9 +346,9 @@ describe('transform', () => { {}, ); expect(options.transform).toEqual([ - [DEFAULT_CSS_PATTERN, '/root/node_modules/jest-regex-util'], + [DEFAULT_CSS_PATTERN, '/root/node_modules/jest-regex-util', {}], [DEFAULT_JS_PATTERN, require.resolve('babel-jest'), {rootMode: 'upward'}], - ['abs-path', '/qux/quux'], + ['abs-path', '/qux/quux', {}], ]); }); }); @@ -822,7 +822,7 @@ describe('Upgrade help', () => { {}, ); - expect(options.transform).toEqual([['.*', '/node_modules/bar/baz']]); + expect(options.transform).toEqual([['.*', '/node_modules/bar/baz', {}]]); expect(options.transformIgnorePatterns).toEqual([ joinForPattern('bar', 'baz'), joinForPattern('qux', 'quux'), @@ -1152,8 +1152,8 @@ describe('preset', () => { '/node_modules/b', ]); expect(options.transform).toEqual([ - ['a', '/node_modules/a'], - ['b', '/node_modules/b'], + ['a', '/node_modules/a', {}], + ['b', '/node_modules/b', {}], ]); }); @@ -1202,10 +1202,10 @@ describe('preset', () => { ); expect(options.transform).toEqual([ - ['e', '/node_modules/ee'], - ['b', '/node_modules/bb'], - ['c', '/node_modules/cc'], - ['a', '/node_modules/aa'], + ['e', '/node_modules/ee', {}], + ['b', '/node_modules/bb', {}], + ['c', '/node_modules/cc', {}], + ['a', '/node_modules/aa', {}], ]); }); diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index c049b27f0524..20a73eca63a2 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -347,6 +347,7 @@ export default class ScriptTransformer { ): TransformResult { const isInternalModule = !!(options && options.isInternalModule); const isCoreModule = !!(options && options.isCoreModule); + const extraGlobals = (options && options.extraGlobals) || []; const content = stripShebang( fileSource || fs.readFileSync(filename, 'utf8'), ); @@ -361,8 +362,6 @@ export default class ScriptTransformer { (this.shouldTransform(filename) || instrument); try { - const extraGlobals = options ? options.extraGlobals : []; - if (willTransform) { const transformedSource = this.transformSource( filename, diff --git a/packages/jest-transform/src/types.ts b/packages/jest-transform/src/types.ts index 541d2b225074..a0b980f26caf 100644 --- a/packages/jest-transform/src/types.ts +++ b/packages/jest-transform/src/types.ts @@ -17,7 +17,7 @@ export type ShouldInstrumentOptions = Pick< }; export type Options = ShouldInstrumentOptions & - Pick & { + Partial> & { isCoreModule?: boolean; isInternalModule?: boolean; };