diff --git a/CHANGELOG.md b/CHANGELOG.md index 1521ee378738..a696213d4770 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ### Features +- `[jest-config]` [**BREAKING**] Move coverage options to project config ([#9633](https://github.com/facebook/jest/pull/9633)) - `[jest-runtime]` Require stack when a module cannot be resolved ([#9681](https://github.com/facebook/jest/pull/9681)) - `[jest-config]` Support ESM config files with `.js` extension ([#9573](https://github.com/facebook/jest/pull/9573)). - `[jest-runtime]` Override `module.createRequire` to return a Jest-compatible `require` function ([#9469](https://github.com/facebook/jest/pull/9469)) diff --git a/TestUtils.ts b/TestUtils.ts index a84f3f8bc630..407f18f79f86 100644 --- a/TestUtils.ts +++ b/TestUtils.ts @@ -12,12 +12,9 @@ const DEFAULT_GLOBAL_CONFIG: Config.GlobalConfig = { changedFilesWithAncestor: false, changedSince: '', collectCoverage: false, - collectCoverageFrom: [], - collectCoverageOnlyFrom: null, coverageDirectory: 'coverage', coverageProvider: 'babel', coverageReporters: [], - coverageThreshold: {global: {}}, detectLeaks: false, detectOpenHandles: false, enabledTestsMap: null, @@ -71,7 +68,10 @@ const DEFAULT_PROJECT_CONFIG: Config.ProjectConfig = { cache: false, cacheDirectory: '/test_cache_dir/', clearMocks: false, + collectCoverageFrom: [], + collectCoverageOnlyFrom: null, coveragePathIgnorePatterns: [], + coverageThreshold: {global: {}}, cwd: '/test_root_dir/', detectLeaks: false, detectOpenHandles: false, diff --git a/docs/WatchPlugins.md b/docs/WatchPlugins.md index 3f99779ed3fa..7fd26d1d4da9 100644 --- a/docs/WatchPlugins.md +++ b/docs/WatchPlugins.md @@ -157,8 +157,6 @@ For stability and safety reasons, only part of the global configuration keys can - [`bail`](configuration.html#bail-number--boolean) - [`changedSince`](cli.html#--changedsince) - [`collectCoverage`](configuration.html#collectcoverage-boolean) -- [`collectCoverageFrom`](configuration.html#collectcoveragefrom-array) -- [`collectCoverageOnlyFrom`](configuration.html#collectcoverageonlyfrom-array) - [`coverageDirectory`](configuration.html#coveragedirectory-string) - [`coverageReporters`](configuration.html#coveragereporters-arraystring) - [`notify`](configuration.html#notify-boolean) diff --git a/e2e/__tests__/__snapshots__/showConfig.test.ts.snap b/e2e/__tests__/__snapshots__/showConfig.test.ts.snap index 7f3d73efee7c..0c5a4c6aa043 100644 --- a/e2e/__tests__/__snapshots__/showConfig.test.ts.snap +++ b/e2e/__tests__/__snapshots__/showConfig.test.ts.snap @@ -9,6 +9,7 @@ exports[`--showConfig outputs config info and exits 1`] = ` "cache": false, "cacheDirectory": "/tmp/jest", "clearMocks": false, + "collectCoverageFrom": [], "coveragePathIgnorePatterns": [ "/node_modules/" ], @@ -82,7 +83,6 @@ exports[`--showConfig outputs config info and exits 1`] = ` "bail": 0, "changedFilesWithAncestor": false, "collectCoverage": false, - "collectCoverageFrom": [], "coverageDirectory": "<>/coverage", "coverageProvider": "babel", "coverageReporters": [ diff --git a/packages/jest-config/src/index.ts b/packages/jest-config/src/index.ts index 85b6e34546d8..d2dc49d1140c 100644 --- a/packages/jest-config/src/index.ts +++ b/packages/jest-config/src/index.ts @@ -109,12 +109,9 @@ const groupOptions = ( changedFilesWithAncestor: options.changedFilesWithAncestor, changedSince: options.changedSince, collectCoverage: options.collectCoverage, - collectCoverageFrom: options.collectCoverageFrom, - collectCoverageOnlyFrom: options.collectCoverageOnlyFrom, coverageDirectory: options.coverageDirectory, coverageProvider: options.coverageProvider, coverageReporters: options.coverageReporters, - coverageThreshold: options.coverageThreshold, detectLeaks: options.detectLeaks, detectOpenHandles: options.detectOpenHandles, enabledTestsMap: options.enabledTestsMap, @@ -167,7 +164,10 @@ const groupOptions = ( cache: options.cache, cacheDirectory: options.cacheDirectory, clearMocks: options.clearMocks, + collectCoverageFrom: options.collectCoverageFrom, + collectCoverageOnlyFrom: options.collectCoverageOnlyFrom, coveragePathIgnorePatterns: options.coveragePathIgnorePatterns, + coverageThreshold: options.coverageThreshold, cwd: options.cwd, dependencyExtractor: options.dependencyExtractor, detectLeaks: options.detectLeaks, diff --git a/packages/jest-core/src/__tests__/watch.test.js b/packages/jest-core/src/__tests__/watch.test.js index af2dea274d7a..43653a5d77aa 100644 --- a/packages/jest-core/src/__tests__/watch.test.js +++ b/packages/jest-core/src/__tests__/watch.test.js @@ -600,11 +600,8 @@ describe('Watch mode flows', () => { ${'✖︎'} | ${'changedFilesWithAncestor'} ${'✔︎'} | ${'changedSince'} ${'✔︎'} | ${'collectCoverage'} - ${'✔︎'} | ${'collectCoverageFrom'} - ${'✔︎'} | ${'collectCoverageOnlyFrom'} ${'✔︎'} | ${'coverageDirectory'} ${'✔︎'} | ${'coverageReporters'} - ${'✖︎'} | ${'coverageThreshold'} ${'✖︎'} | ${'detectLeaks'} ${'✖︎'} | ${'detectOpenHandles'} ${'✖︎'} | ${'enabledTestsMap'} diff --git a/packages/jest-core/src/lib/__tests__/__snapshots__/log_debug_messages.test.ts.snap b/packages/jest-core/src/lib/__tests__/__snapshots__/log_debug_messages.test.ts.snap index 3be6c4ebb716..3148b01fb27a 100644 --- a/packages/jest-core/src/lib/__tests__/__snapshots__/log_debug_messages.test.ts.snap +++ b/packages/jest-core/src/lib/__tests__/__snapshots__/log_debug_messages.test.ts.snap @@ -8,7 +8,12 @@ exports[`prints the config object 1`] = ` "cache": false, "cacheDirectory": "/test_cache_dir/", "clearMocks": false, + "collectCoverageFrom": [], + "collectCoverageOnlyFrom": null, "coveragePathIgnorePatterns": [], + "coverageThreshold": { + "global": {} + }, "cwd": "/test_root_dir/", "detectLeaks": false, "detectOpenHandles": false, @@ -68,14 +73,9 @@ exports[`prints the config object 1`] = ` "changedFilesWithAncestor": false, "changedSince": "", "collectCoverage": false, - "collectCoverageFrom": [], - "collectCoverageOnlyFrom": null, "coverageDirectory": "coverage", "coverageProvider": "babel", "coverageReporters": [], - "coverageThreshold": { - "global": {} - }, "detectLeaks": false, "detectOpenHandles": false, "enabledTestsMap": null, diff --git a/packages/jest-core/src/lib/update_global_config.ts b/packages/jest-core/src/lib/update_global_config.ts index 992a03631bdd..f3260ebdf393 100644 --- a/packages/jest-core/src/lib/update_global_config.ts +++ b/packages/jest-core/src/lib/update_global_config.ts @@ -56,14 +56,6 @@ export default ( newConfig.collectCoverage = options.collectCoverage || false; } - if (options.collectCoverageFrom !== undefined) { - newConfig.collectCoverageFrom = options.collectCoverageFrom; - } - - if (options.collectCoverageOnlyFrom !== undefined) { - newConfig.collectCoverageOnlyFrom = options.collectCoverageOnlyFrom; - } - if (options.coverageDirectory !== undefined) { newConfig.coverageDirectory = options.coverageDirectory; } diff --git a/packages/jest-core/src/watch.ts b/packages/jest-core/src/watch.ts index 49c74bf981bc..0fa4f60b73e5 100644 --- a/packages/jest-core/src/watch.ts +++ b/packages/jest-core/src/watch.ts @@ -103,8 +103,6 @@ export default function watch( bail, changedSince, collectCoverage, - collectCoverageFrom, - collectCoverageOnlyFrom, coverageDirectory, coverageReporters, mode, @@ -122,8 +120,6 @@ export default function watch( bail, changedSince, collectCoverage, - collectCoverageFrom, - collectCoverageOnlyFrom, coverageDirectory, coverageReporters, mode, diff --git a/packages/jest-reporters/src/__tests__/coverage_reporter.test.js b/packages/jest-reporters/src/__tests__/coverage_reporter.test.js index 7e1cf5c4ceb6..10d5058918b7 100644 --- a/packages/jest-reporters/src/__tests__/coverage_reporter.test.js +++ b/packages/jest-reporters/src/__tests__/coverage_reporter.test.js @@ -133,19 +133,23 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, + }, + { + maxWorkers: 2, + }, + ); + const context = { + config: { coverageThreshold: { global: { statements: 100, }, }, }, - { - maxWorkers: 2, - }, - ); + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError().message.split('\n')).toHaveLength(1); }); @@ -167,15 +171,19 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, - coverageThreshold: covThreshold, }, { maxWorkers: 2, }, ); + const context = { + config: { + coverageThreshold: covThreshold, + }, + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError().message.split('\n')).toHaveLength(5); }); @@ -197,15 +205,19 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, - coverageThreshold: covThreshold, }, { maxWorkers: 2, }, ); + const context = { + config: { + coverageThreshold: covThreshold, + }, + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError()).toBeUndefined(); }); @@ -215,19 +227,23 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, + }, + { + maxWorkers: 2, + }, + ); + const context = { + config: { coverageThreshold: { 'path-test-files/non_covered_file.js': { statements: 100, }, }, }, - { - maxWorkers: 2, - }, - ); + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError().message.split('\n')).toHaveLength(1); }); @@ -237,19 +253,23 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, + }, + { + maxWorkers: 2, + }, + ); + const context = { + config: { coverageThreshold: { './path-test-files/glob-path/': { statements: 100, }, }, }, - { - maxWorkers: 2, - }, - ); + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError().message.split('\n')).toHaveLength(1); }); @@ -259,19 +279,23 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, + }, + { + maxWorkers: 2, + }, + ); + const context = { + config: { coverageThreshold: { './path-test-files/glob-path/': { statements: 40, }, }, }, - { - maxWorkers: 2, - }, - ); + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError()).toBeUndefined(); }); @@ -281,19 +305,23 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, + }, + { + maxWorkers: 2, + }, + ); + const context = { + config: { coverageThreshold: { './path/doesnt/exist': { statements: 40, }, }, }, - { - maxWorkers: 2, - }, - ); + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError().message.split('\n')).toHaveLength(1); }); @@ -305,6 +333,13 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, + }, + { + maxWorkers: 2, + }, + ); + const context = { + config: { coverageThreshold: { './path-test-files/': { statements: 50, @@ -314,13 +349,10 @@ describe('onRunComplete', () => { }, }, }, - { - maxWorkers: 2, - }, - ); + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError()).toBeUndefined(); }); @@ -346,15 +378,19 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, - coverageThreshold: covThreshold, }, { maxWorkers: 2, }, ); + const context = { + config: { + coverageThreshold: covThreshold, + }, + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError()).toBeUndefined(); }); @@ -366,6 +402,13 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, + }, + { + maxWorkers: 2, + }, + ); + const context = { + config: { coverageThreshold: { './path-test-files/100pc_coverage_file.js': { statements: 100, @@ -375,15 +418,12 @@ describe('onRunComplete', () => { }, }, }, - { - maxWorkers: 2, - }, - ); + }; testReporter.log = jest.fn(); // 100% coverage file is removed from overall coverage so // coverage drops to < 50% return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError().message.split('\n')).toHaveLength(1); }); @@ -393,6 +433,13 @@ describe('onRunComplete', () => { const testReporter = new CoverageReporter( { collectCoverage: true, + }, + { + maxWorkers: 2, + }, + ); + const context = { + config: { coverageThreshold: { './path-test-files/': { statements: 50, @@ -408,13 +455,10 @@ describe('onRunComplete', () => { }, }, }, - { - maxWorkers: 2, - }, - ); + }; testReporter.log = jest.fn(); return testReporter - .onRunComplete(new Set(), {}, mockAggResults) + .onRunComplete(new Set([context]), {}, mockAggResults) .then(() => { expect(testReporter.getLastError()).toBeUndefined(); }); diff --git a/packages/jest-reporters/src/__tests__/get_watermarks.test.ts b/packages/jest-reporters/src/__tests__/get_watermarks.test.ts index 2b47c5159e09..d559c58b5d12 100644 --- a/packages/jest-reporters/src/__tests__/get_watermarks.test.ts +++ b/packages/jest-reporters/src/__tests__/get_watermarks.test.ts @@ -6,39 +6,70 @@ */ import getWatermarks from '../get_watermarks'; -import {makeGlobalConfig} from '../../../../TestUtils'; +import {makeProjectConfig} from '../../../../TestUtils'; describe('getWatermarks', () => { - test(`that watermarks use thresholds as upper target`, () => { - const watermarks = getWatermarks( - makeGlobalConfig({ - coverageThreshold: { - global: { - branches: 100, - functions: 100, - lines: 100, - statements: 100, + describe('when a single context is given', () => { + test(`that watermarks use thresholds as upper target`, () => { + const context = { + config: makeProjectConfig({ + coverageThreshold: { + global: { + branches: 100, + functions: 100, + lines: 100, + statements: 100, + }, }, - }, - }), - ); - - expect(watermarks).toEqual({ - branches: [expect.any(Number), 100], - functions: [expect.any(Number), 100], - lines: [expect.any(Number), 100], - statements: [expect.any(Number), 100], + }), + }; + const watermarks = getWatermarks(new Set([context])); + + expect(watermarks).toEqual({ + branches: [expect.any(Number), 100], + functions: [expect.any(Number), 100], + lines: [expect.any(Number), 100], + statements: [expect.any(Number), 100], + }); }); }); - test(`that watermarks are created always created`, () => { - const watermarks = getWatermarks(makeGlobalConfig()); + describe('when no contexts are given', () => { + test(`that watermarks are created always created`, () => { + const watermarks = getWatermarks(new Set()); + + expect(watermarks).toEqual({ + branches: [expect.any(Number), expect.any(Number)], + functions: [expect.any(Number), expect.any(Number)], + lines: [expect.any(Number), expect.any(Number)], + statements: [expect.any(Number), expect.any(Number)], + }); + }); + }); + + describe('when multiple contexts are given', () => { + test(`that watermarks are created always created`, () => { + const context = { + config: makeProjectConfig({ + coverageThreshold: { + global: { + branches: 100, + functions: 100, + lines: 100, + statements: 100, + }, + }, + }), + }; + + const watermarks = getWatermarks(new Set([context, context])); - expect(watermarks).toEqual({ - branches: [expect.any(Number), expect.any(Number)], - functions: [expect.any(Number), expect.any(Number)], - lines: [expect.any(Number), expect.any(Number)], - statements: [expect.any(Number), expect.any(Number)], + expect(watermarks).toEqual({ + branches: [expect.any(Number), expect.any(Number)], + functions: [expect.any(Number), expect.any(Number)], + lines: [expect.any(Number), expect.any(Number)], + statements: [expect.any(Number), expect.any(Number)], + }); }); }); }); diff --git a/packages/jest-reporters/src/coverage_reporter.ts b/packages/jest-reporters/src/coverage_reporter.ts index b769743e2ff6..d2e27130b2e8 100644 --- a/packages/jest-reporters/src/coverage_reporter.ts +++ b/packages/jest-reporters/src/coverage_reporter.ts @@ -100,7 +100,7 @@ export default class CoverageReporter extends BaseReporter { aggregatedResults: AggregatedResult, ): Promise { await this._addUntestedFiles(contexts); - const {map, reportContext} = await this._getCoverageResult(); + const {map, reportContext} = await this._getCoverageResult(contexts); try { const coverageReporters = this._globalConfig.coverageReporters || []; @@ -133,24 +133,17 @@ export default class CoverageReporter extends BaseReporter { ); } - // @ts-ignore - this._checkThreshold(map); + this._checkThresholds(map, contexts); } private async _addUntestedFiles(contexts: Set): Promise { const files: Array<{config: Config.ProjectConfig; path: string}> = []; contexts.forEach(context => { - const config = context.config; - if ( - this._globalConfig.collectCoverageFrom && - this._globalConfig.collectCoverageFrom.length - ) { + const {config} = context; + if (config.collectCoverageFrom && config.collectCoverageFrom.length) { context.hasteFS - .matchFilesWithGlob( - this._globalConfig.collectCoverageFrom, - config.rootDir, - ) + .matchFilesWithGlob(config.collectCoverageFrom, config.rootDir) .forEach(filePath => files.push({ config, @@ -253,9 +246,19 @@ export default class CoverageReporter extends BaseReporter { } } - private _checkThreshold(map: istanbulCoverage.CoverageMap) { - const {coverageThreshold} = this._globalConfig; + private _checkThresholds( + map: istanbulCoverage.CoverageMap, + contexts: Set, + ) { + contexts.forEach(context => + this._checkThresholdForContext(map, context.config.coverageThreshold), + ); + } + private _checkThresholdForContext( + map: istanbulCoverage.CoverageMap, + coverageThreshold?: Config.CoverageThreshold, + ) { if (coverageThreshold) { function check( name: string, @@ -444,7 +447,9 @@ export default class CoverageReporter extends BaseReporter { } } - private async _getCoverageResult(): Promise<{ + private async _getCoverageResult( + contexts: Set, + ): Promise<{ map: istanbulCoverage.CoverageMap; reportContext: istanbulReport.Context; }> { @@ -506,7 +511,7 @@ export default class CoverageReporter extends BaseReporter { const reportContext = istanbulReport.createContext({ coverageMap: map, dir: this._globalConfig.coverageDirectory, - watermarks: getWatermarks(this._globalConfig), + watermarks: getWatermarks(contexts), }); return {map, reportContext}; @@ -521,7 +526,7 @@ export default class CoverageReporter extends BaseReporter { dir: this._globalConfig.coverageDirectory, // @ts-ignore sourceFinder: this._sourceMapStore.sourceFinder, - watermarks: getWatermarks(this._globalConfig), + watermarks: getWatermarks(contexts), }, ); diff --git a/packages/jest-reporters/src/generateEmptyCoverage.ts b/packages/jest-reporters/src/generateEmptyCoverage.ts index 62ab4c023f2c..e84d80a10f9b 100644 --- a/packages/jest-reporters/src/generateEmptyCoverage.ts +++ b/packages/jest-reporters/src/generateEmptyCoverage.ts @@ -35,8 +35,6 @@ export default function ( const coverageOptions = { changedFiles, collectCoverage: globalConfig.collectCoverage, - collectCoverageFrom: globalConfig.collectCoverageFrom, - collectCoverageOnlyFrom: globalConfig.collectCoverageOnlyFrom, coverageProvider: globalConfig.coverageProvider, }; let coverageWorkerResult: CoverageWorkerResult | null = null; diff --git a/packages/jest-reporters/src/get_watermarks.ts b/packages/jest-reporters/src/get_watermarks.ts index 6c3bd174bf25..e3552d03badf 100644 --- a/packages/jest-reporters/src/get_watermarks.ts +++ b/packages/jest-reporters/src/get_watermarks.ts @@ -7,13 +7,19 @@ import type {Config} from '@jest/types'; import istanbulReport = require('istanbul-lib-report'); +import type {Context} from './types'; export default function getWatermarks( - config: Config.GlobalConfig, + contexts: Set>, ): istanbulReport.Watermarks { const defaultWatermarks = istanbulReport.getDefaultWatermarks(); - const {coverageThreshold} = config; + if (contexts.size !== 1) { + return defaultWatermarks; + } + + const firstAndOnlyContext = contexts.values().next().value; + const {coverageThreshold} = firstAndOnlyContext.config; if (!coverageThreshold || !coverageThreshold.global) { return defaultWatermarks; diff --git a/packages/jest-runner/src/runTest.ts b/packages/jest-runner/src/runTest.ts index a617bc9d510c..65d7029bbbef 100644 --- a/packages/jest-runner/src/runTest.ts +++ b/packages/jest-runner/src/runTest.ts @@ -156,8 +156,6 @@ async function runTestInternal( runtime = new Runtime(config, environment, resolver, cacheFS, { changedFiles: context && context.changedFiles, collectCoverage: globalConfig.collectCoverage, - collectCoverageFrom: globalConfig.collectCoverageFrom, - collectCoverageOnlyFrom: globalConfig.collectCoverageOnlyFrom, coverageProvider: globalConfig.coverageProvider, }); diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index 39a43443c26c..0120bab0a2ef 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -135,8 +135,6 @@ class Runtime { this._coverageOptions = coverageOptions || { changedFiles: undefined, collectCoverage: false, - collectCoverageFrom: [], - collectCoverageOnlyFrom: undefined, coverageProvider: 'babel', }; this._currentlyExecutingModulePath = ''; @@ -496,8 +494,6 @@ class Runtime { ...options, changedFiles: this._coverageOptions.changedFiles, collectCoverage: this._coverageOptions.collectCoverage, - collectCoverageFrom: this._coverageOptions.collectCoverageFrom, - collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom, coverageProvider: this._coverageOptions.coverageProvider, }; } diff --git a/packages/jest-transform/src/__tests__/__snapshots__/script_transformer.test.js.snap b/packages/jest-transform/src/__tests__/__snapshots__/script_transformer.test.js.snap index fe9bb5ceb3ec..b8d83f14fc5f 100644 --- a/packages/jest-transform/src/__tests__/__snapshots__/script_transformer.test.js.snap +++ b/packages/jest-transform/src/__tests__/__snapshots__/script_transformer.test.js.snap @@ -8,7 +8,12 @@ Object { "cache": true, "cacheDirectory": "/cache/", "clearMocks": false, + "collectCoverageFrom": Array [], + "collectCoverageOnlyFrom": null, "coveragePathIgnorePatterns": Array [], + "coverageThreshold": Object { + "global": Object {}, + }, "cwd": "/test_root_dir/", "detectLeaks": false, "detectOpenHandles": false, @@ -228,7 +233,7 @@ exports[`ScriptTransformer uses multiple preprocessors 1`] = ` const TRANSFORMED = { filename: '/fruits/banana.js', script: 'module.exports = "banana";', - config: '{"automock":false,"browser":false,"cache":true,"cacheDirectory":"/cache/","clearMocks":false,"coveragePathIgnorePatterns":[],"cwd":"/test_root_dir/","detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"extraGlobals":[],"filter":null,"forceCoverageMatch":[],"globalSetup":null,"globalTeardown":null,"globals":{},"haste":{"providesModuleNodeModules":[]},"moduleDirectories":[],"moduleFileExtensions":["js"],"moduleLoader":"/test_module_loader_path","moduleNameMapper":[],"modulePathIgnorePatterns":[],"modulePaths":[],"name":"test","prettierPath":"prettier","resetMocks":false,"resetModules":false,"resolver":null,"restoreMocks":false,"rootDir":"/","roots":[],"runner":"jest-runner","setupFiles":[],"setupFilesAfterEnv":[],"skipFilter":false,"skipNodeResolution":false,"snapshotResolver":null,"snapshotSerializers":[],"testEnvironment":"node","testEnvironmentOptions":{},"testLocationInResults":false,"testMatch":[],"testPathIgnorePatterns":[],"testRegex":["\\\\.test\\\\.js$"],"testRunner":"jest-jasmine2","testURL":"http://localhost","timers":"real","transform":[["^.+\\\\.js$","test_preprocessor"],["^.+\\\\.css$","css-preprocessor"]],"transformIgnorePatterns":["/node_modules/"],"unmockedModulePathPatterns":null,"watchPathIgnorePatterns":[]}', + config: '{"automock":false,"browser":false,"cache":true,"cacheDirectory":"/cache/","clearMocks":false,"collectCoverageFrom":[],"collectCoverageOnlyFrom":null,"coveragePathIgnorePatterns":[],"coverageThreshold":{"global":{}},"cwd":"/test_root_dir/","detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"extraGlobals":[],"filter":null,"forceCoverageMatch":[],"globalSetup":null,"globalTeardown":null,"globals":{},"haste":{"providesModuleNodeModules":[]},"moduleDirectories":[],"moduleFileExtensions":["js"],"moduleLoader":"/test_module_loader_path","moduleNameMapper":[],"modulePathIgnorePatterns":[],"modulePaths":[],"name":"test","prettierPath":"prettier","resetMocks":false,"resetModules":false,"resolver":null,"restoreMocks":false,"rootDir":"/","roots":[],"runner":"jest-runner","setupFiles":[],"setupFilesAfterEnv":[],"skipFilter":false,"skipNodeResolution":false,"snapshotResolver":null,"snapshotSerializers":[],"testEnvironment":"node","testEnvironmentOptions":{},"testLocationInResults":false,"testMatch":[],"testPathIgnorePatterns":[],"testRegex":["\\\\.test\\\\.js$"],"testRunner":"jest-jasmine2","testURL":"http://localhost","timers":"real","transform":[["^.+\\\\.js$","test_preprocessor"],["^.+\\\\.css$","css-preprocessor"]],"transformIgnorePatterns":["/node_modules/"],"unmockedModulePathPatterns":null,"watchPathIgnorePatterns":[]}', }; `; @@ -245,7 +250,7 @@ exports[`ScriptTransformer uses the supplied preprocessor 1`] = ` const TRANSFORMED = { filename: '/fruits/banana.js', script: 'module.exports = "banana";', - config: '{"automock":false,"browser":false,"cache":true,"cacheDirectory":"/cache/","clearMocks":false,"coveragePathIgnorePatterns":[],"cwd":"/test_root_dir/","detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"extraGlobals":[],"filter":null,"forceCoverageMatch":[],"globalSetup":null,"globalTeardown":null,"globals":{},"haste":{"providesModuleNodeModules":[]},"moduleDirectories":[],"moduleFileExtensions":["js"],"moduleLoader":"/test_module_loader_path","moduleNameMapper":[],"modulePathIgnorePatterns":[],"modulePaths":[],"name":"test","prettierPath":"prettier","resetMocks":false,"resetModules":false,"resolver":null,"restoreMocks":false,"rootDir":"/","roots":[],"runner":"jest-runner","setupFiles":[],"setupFilesAfterEnv":[],"skipFilter":false,"skipNodeResolution":false,"snapshotResolver":null,"snapshotSerializers":[],"testEnvironment":"node","testEnvironmentOptions":{},"testLocationInResults":false,"testMatch":[],"testPathIgnorePatterns":[],"testRegex":["\\\\.test\\\\.js$"],"testRunner":"jest-jasmine2","testURL":"http://localhost","timers":"real","transform":[["^.+\\\\.js$","test_preprocessor"]],"transformIgnorePatterns":["/node_modules/"],"unmockedModulePathPatterns":null,"watchPathIgnorePatterns":[]}', + config: '{"automock":false,"browser":false,"cache":true,"cacheDirectory":"/cache/","clearMocks":false,"collectCoverageFrom":[],"collectCoverageOnlyFrom":null,"coveragePathIgnorePatterns":[],"coverageThreshold":{"global":{}},"cwd":"/test_root_dir/","detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"extraGlobals":[],"filter":null,"forceCoverageMatch":[],"globalSetup":null,"globalTeardown":null,"globals":{},"haste":{"providesModuleNodeModules":[]},"moduleDirectories":[],"moduleFileExtensions":["js"],"moduleLoader":"/test_module_loader_path","moduleNameMapper":[],"modulePathIgnorePatterns":[],"modulePaths":[],"name":"test","prettierPath":"prettier","resetMocks":false,"resetModules":false,"resolver":null,"restoreMocks":false,"rootDir":"/","roots":[],"runner":"jest-runner","setupFiles":[],"setupFilesAfterEnv":[],"skipFilter":false,"skipNodeResolution":false,"snapshotResolver":null,"snapshotSerializers":[],"testEnvironment":"node","testEnvironmentOptions":{},"testLocationInResults":false,"testMatch":[],"testPathIgnorePatterns":[],"testRegex":["\\\\.test\\\\.js$"],"testRunner":"jest-jasmine2","testURL":"http://localhost","timers":"real","transform":[["^.+\\\\.js$","test_preprocessor"]],"transformIgnorePatterns":["/node_modules/"],"unmockedModulePathPatterns":null,"watchPathIgnorePatterns":[]}', }; `; diff --git a/packages/jest-transform/src/__tests__/should_instrument.test.ts b/packages/jest-transform/src/__tests__/should_instrument.test.ts index 1e1702d746f0..4e048f58e193 100644 --- a/packages/jest-transform/src/__tests__/should_instrument.test.ts +++ b/packages/jest-transform/src/__tests__/should_instrument.test.ts @@ -80,20 +80,22 @@ describe('shouldInstrument', () => { it('should return true when file is in collectCoverageOnlyFrom when provided', () => { testShouldInstrument( 'collect/only/from/here.js', + {}, { + ...defaultConfig, collectCoverageOnlyFrom: {'collect/only/from/here.js': true}, }, - defaultConfig, ); }); it('should return true when filename matches collectCoverageFrom', () => { testShouldInstrument( 'do/collect/coverage.js', + {}, { + ...defaultConfig, collectCoverageFrom: ['!**/dont/**/*.js', '**/do/**/*.js'], }, - defaultConfig, ); }); @@ -170,20 +172,22 @@ describe('shouldInstrument', () => { it('when file is not in collectCoverageOnlyFrom when provided', () => { testShouldInstrument( 'source_file.js', + {}, { + ...defaultConfig, collectCoverageOnlyFrom: {'collect/only/from/here.js': true}, }, - defaultConfig, ); }); it('when filename does not match collectCoverageFrom', () => { testShouldInstrument( 'dont/collect/coverage.js', + {}, { + ...defaultConfig, collectCoverageFrom: ['!**/dont/**/*.js', '**/do/**/*.js'], }, - defaultConfig, ); }); diff --git a/packages/jest-transform/src/shouldInstrument.ts b/packages/jest-transform/src/shouldInstrument.ts index e9d75afdbc63..c2cf84facee4 100644 --- a/packages/jest-transform/src/shouldInstrument.ts +++ b/packages/jest-transform/src/shouldInstrument.ts @@ -49,19 +49,19 @@ export default function shouldInstrument( if ( // This configuration field contains an object in the form of: // {'path/to/file.js': true} - options.collectCoverageOnlyFrom && - !options.collectCoverageOnlyFrom[filename] + config.collectCoverageOnlyFrom && + !config.collectCoverageOnlyFrom[filename] ) { return false; } if ( // still cover if `only` is specified - !options.collectCoverageOnlyFrom && - options.collectCoverageFrom.length && + !config.collectCoverageOnlyFrom && + config.collectCoverageFrom.length && micromatch( [replacePathSepForGlob(path.relative(config.rootDir, filename))], - options.collectCoverageFrom, + config.collectCoverageFrom, ).length === 0 ) { return false; diff --git a/packages/jest-transform/src/types.ts b/packages/jest-transform/src/types.ts index cfdfb97d4747..b093c879a4be 100644 --- a/packages/jest-transform/src/types.ts +++ b/packages/jest-transform/src/types.ts @@ -10,10 +10,7 @@ import type {Config} from '@jest/types'; export type ShouldInstrumentOptions = Pick< Config.GlobalConfig, - | 'collectCoverage' - | 'collectCoverageFrom' - | 'collectCoverageOnlyFrom' - | 'coverageProvider' + 'collectCoverage' | 'coverageProvider' > & { changedFiles?: Set; }; diff --git a/packages/jest-types/src/Config.ts b/packages/jest-types/src/Config.ts index 7169f8e13f18..77bfeece9cf0 100644 --- a/packages/jest-types/src/Config.ts +++ b/packages/jest-types/src/Config.ts @@ -226,7 +226,7 @@ export type CoverageThresholdValue = { statements?: number; }; -type CoverageThreshold = { +export type CoverageThreshold = { [path: string]: CoverageThresholdValue; global: CoverageThresholdValue; }; @@ -236,15 +236,10 @@ export type GlobalConfig = { changedSince?: string; changedFilesWithAncestor: boolean; collectCoverage: boolean; - collectCoverageFrom: Array; - collectCoverageOnlyFrom?: { - [key: string]: boolean; - }; coverageDirectory: string; coveragePathIgnorePatterns?: Array; coverageProvider: CoverageProvider; coverageReporters: Array; - coverageThreshold?: CoverageThreshold; detectLeaks: boolean; detectOpenHandles: boolean; enabledTestsMap?: { @@ -305,7 +300,12 @@ export type ProjectConfig = { cache: boolean; cacheDirectory: Path; clearMocks: boolean; + collectCoverageFrom: Array; + collectCoverageOnlyFrom?: { + [key: string]: boolean; + }; coveragePathIgnorePatterns: Array; + coverageThreshold?: CoverageThreshold; cwd: Path; dependencyExtractor?: string; detectLeaks: boolean; diff --git a/packages/jest-watcher/src/types.ts b/packages/jest-watcher/src/types.ts index 4890c56b8f6e..7a31362c623b 100644 --- a/packages/jest-watcher/src/types.ts +++ b/packages/jest-watcher/src/types.ts @@ -50,8 +50,6 @@ export type AllowedConfigOptions = Partial< | 'bail' | 'changedSince' | 'collectCoverage' - | 'collectCoverageFrom' - | 'collectCoverageOnlyFrom' | 'coverageDirectory' | 'coverageReporters' | 'notify'