From 619e01d045e3d401d1d2986c6b7cbfef8f9a40b1 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Sun, 17 Nov 2019 21:10:29 +0100 Subject: [PATCH] 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;