From 4d573e45534ad759e19f1bf81018e0d0c86a50ab Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Wed, 16 Feb 2022 09:08:05 +0100 Subject: [PATCH 1/6] chore: use `this` in `expect.extend` example (#12401) --- examples/expect-extend/toBeWithinRange.ts | 59 ++++++++++++----------- 1 file changed, 32 insertions(+), 27 deletions(-) diff --git a/examples/expect-extend/toBeWithinRange.ts b/examples/expect-extend/toBeWithinRange.ts index 55ce710f440c..fa0bef2a66ec 100644 --- a/examples/expect-extend/toBeWithinRange.ts +++ b/examples/expect-extend/toBeWithinRange.ts @@ -8,34 +8,39 @@ import {expect} from '@jest/globals'; import type {MatcherFunction} from 'expect'; -const toBeWithinRange: MatcherFunction<[floor: number, ceiling: number]> = ( - actual: unknown, - floor: unknown, - ceiling: unknown, -) => { - if ( - typeof actual !== 'number' || - typeof floor !== 'number' || - typeof ceiling !== 'number' - ) { - throw new Error('These must be of type number!'); - } +const toBeWithinRange: MatcherFunction<[floor: number, ceiling: number]> = + function (actual: unknown, floor: unknown, ceiling: unknown) { + if ( + typeof actual !== 'number' || + typeof floor !== 'number' || + typeof ceiling !== 'number' + ) { + throw new Error('These must be of type number!'); + } - const pass = actual >= floor && actual <= ceiling; - if (pass) { - return { - message: () => - `expected ${actual} not to be within range ${floor} - ${ceiling}`, - pass: true, - }; - } else { - return { - message: () => - `expected ${actual} to be within range ${floor} - ${ceiling}`, - pass: false, - }; - } -}; + const pass = actual >= floor && actual <= ceiling; + if (pass) { + return { + message: () => + `expected ${this.utils.printReceived( + actual, + )} not to be within range ${this.utils.printExpected( + `${floor} - ${ceiling}`, + )}`, + pass: true, + }; + } else { + return { + message: () => + `expected ${this.utils.printReceived( + actual, + )} to be within range ${this.utils.printExpected( + `${floor} - ${ceiling}`, + )}`, + pass: false, + }; + } + }; expect.extend({ toBeWithinRange, From adf8526f5e931a9a4ddb0b3305e224dc6ce06e69 Mon Sep 17 00:00:00 2001 From: Tommaso Bossi Date: Wed, 16 Feb 2022 09:54:41 +0100 Subject: [PATCH 2/6] feat: ESM data uri import and mock (#12392) --- CHANGELOG.md | 1 + .../moduleNameMapper.test.ts.snap | 4 +- .../__snapshots__/nativeEsm.test.ts.snap | 2 +- e2e/native-esm/__tests__/native-esm.test.js | 95 +++++++++++++++++++ e2e/native-esm/staticDataImport.js | 13 +++ packages/jest-resolve/src/resolver.ts | 3 + packages/jest-runtime/src/index.ts | 83 ++++++++++++++++ 7 files changed, 198 insertions(+), 3 deletions(-) create mode 100644 e2e/native-esm/staticDataImport.js diff --git a/CHANGELOG.md b/CHANGELOG.md index dbe5a08c76ce..877a2233c742 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - `[jest-environment-node]` [**BREAKING**] Add default `node` and `node-addon` conditions to `exportConditions` for `node` environment ([#11924](https://github.com/facebook/jest/pull/11924)) - `[@jest/expect-utils]` New module exporting utils for `expect` ([#12323](https://github.com/facebook/jest/pull/12323)) - `[jest-resolver]` [**BREAKING**] Add support for `package.json` `exports` ([11961](https://github.com/facebook/jest/pull/11961)) +- `[jest-resolve, jest-runtime]` Add support for `data:` URI import and mock ([#12392](https://github.com/facebook/jest/pull/12392)) - `[@jes/schemas]` New module for JSON schemas for Jest's config ([#12384](https://github.com/facebook/jest/pull/12384)) - `[jest-worker]` [**BREAKING**] Allow only absolute `workerPath` ([#12343](https://github.com/facebook/jest/pull/12343)) diff --git a/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap b/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap index b756a376579a..d382ec9c3f30 100644 --- a/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap +++ b/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap @@ -41,7 +41,7 @@ exports[`moduleNameMapper wrong array configuration 1`] = ` 12 | module.exports = () => 'test'; 13 | - at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:568:17) + at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:572:17) at Object.require (index.js:10:1)" `; @@ -70,6 +70,6 @@ exports[`moduleNameMapper wrong configuration 1`] = ` 12 | module.exports = () => 'test'; 13 | - at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:568:17) + at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:572:17) at Object.require (index.js:10:1)" `; diff --git a/e2e/__tests__/__snapshots__/nativeEsm.test.ts.snap b/e2e/__tests__/__snapshots__/nativeEsm.test.ts.snap index 3c01bb2e69eb..6a6886d95fd3 100644 --- a/e2e/__tests__/__snapshots__/nativeEsm.test.ts.snap +++ b/e2e/__tests__/__snapshots__/nativeEsm.test.ts.snap @@ -2,7 +2,7 @@ exports[`on node >=12.16.0 runs test with native ESM 1`] = ` "Test Suites: 1 passed, 1 total -Tests: 21 passed, 21 total +Tests: 32 passed, 32 total Snapshots: 0 total Time: <> Ran all test suites matching /native-esm.test.js/i." diff --git a/e2e/native-esm/__tests__/native-esm.test.js b/e2e/native-esm/__tests__/native-esm.test.js index aa6c6456d7c7..73a652bdac5e 100644 --- a/e2e/native-esm/__tests__/native-esm.test.js +++ b/e2e/native-esm/__tests__/native-esm.test.js @@ -195,3 +195,98 @@ test('can mock module', async () => { test('supports imports using "node:" prefix', () => { expect(dns).toBe(prefixDns); }); + +test('supports imports from "data:text/javascript" URI with charset=utf-8 encoding', async () => { + const code = 'export const something = "some value"'; + const importedEncoded = await import( + `data:text/javascript;charset=utf-8,${encodeURIComponent(code)}` + ); + expect(importedEncoded.something).toBe('some value'); +}); + +test('supports imports from "data:text/javascript" URI with base64 encoding', async () => { + const code = 'export const something = "some value"'; + const importedBase64 = await import( + `data:text/javascript;base64,${Buffer.from(code).toString('base64')}` + ); + expect(importedBase64.something).toBe('some value'); +}); + +test('supports imports from "data:text/javascript" URI without explicit encoding', async () => { + const code = 'export const something = "some value"'; + const importedEncoded = await import( + `data:text/javascript,${encodeURIComponent(code)}` + ); + expect(importedEncoded.something).toBe('some value'); +}); + +test('imports from "data:text/javascript" URI with invalid encoding fail', async () => { + const code = 'export const something = "some value"'; + await expect( + async () => + await import( + `data:text/javascript;charset=badEncoding,${encodeURIComponent(code)}` + ), + ).rejects.toThrow('Invalid data URI'); +}); + +test('imports from "data:" URI with invalid mime type fail', async () => { + const code = 'export const something = "some value"'; + await expect( + async () => await import(`data:something/else,${encodeURIComponent(code)}`), + ).rejects.toThrow('Invalid data URI'); +}); + +test('imports from "data:text/javascript" URI with invalid data fail', async () => { + await expect( + async () => + await import('data:text/javascript;charset=utf-8,so(me)+.-gibberish'), + ).rejects.toThrow("Unexpected token '.'"); +}); + +test('imports from "data:application/wasm" URI not supported', async () => { + await expect( + async () => await import('data:application/wasm,96cafe00babe'), + ).rejects.toThrow('WASM is currently not supported'); +}); + +test('supports imports from "data:application/json" URI', async () => { + const data = await import('data:application/json,{"foo": "bar"}'); + expect(data.default).toEqual({foo: 'bar'}); +}); + +test('supports static "data:" URI import', async () => { + const module = await import('../staticDataImport.js'); + expect(module.value()).toEqual({bar: {obj: 456}, foo: '123'}); +}); + +test('imports from "data:" URI is properly cached', async () => { + const code = + 'export const wrapper = {value: 123}\nexport const set = (value) => wrapper.value = value'; + const data1 = await import( + `data:text/javascript;charset=utf-8,${encodeURIComponent(code)}` + ); + expect(data1.wrapper.value).toBe(123); + data1.set(234); + expect(data1.wrapper.value).toBe(234); + const data2 = await import( + `data:text/javascript;base64,${Buffer.from(code).toString('base64')}` + ); + expect(data2.wrapper.value).toBe(123); + const data3 = await import( + `data:text/javascript;charset=utf-8,${encodeURIComponent(code)}` + ); + expect(data3.wrapper.value).toBe(234); +}); + +test('can mock "data:" URI module', async () => { + const code = 'export const something = "some value"'; + const dataModule = `data:text/javascript;base64,${Buffer.from(code).toString( + 'base64', + )}`; + jestObject.unstable_mockModule(dataModule, () => ({foo: 'bar'}), { + virtual: true, + }); + const mocked = await import(dataModule); + expect(mocked.foo).toBe('bar'); +}); diff --git a/e2e/native-esm/staticDataImport.js b/e2e/native-esm/staticDataImport.js new file mode 100644 index 000000000000..f26873dc7b48 --- /dev/null +++ b/e2e/native-esm/staticDataImport.js @@ -0,0 +1,13 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import bar from 'data:application/json,{"obj": 456}'; +import {foo} from 'data:text/javascript,export const foo = "123"'; + +export function value() { + return {bar, foo}; +} diff --git a/packages/jest-resolve/src/resolver.ts b/packages/jest-resolve/src/resolver.ts index 4dacbc8fc5fd..75c4018e4088 100644 --- a/packages/jest-resolve/src/resolver.ts +++ b/packages/jest-resolve/src/resolver.ts @@ -370,6 +370,9 @@ export default class Resolver { if (this.isCoreModule(moduleName)) { return moduleName; } + if (moduleName.startsWith('data:')) { + return moduleName; + } return this._isModuleResolved(from, moduleName) ? this.getModule(moduleName) : this._getVirtualMockPath(virtualMocks, from, moduleName, options); diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index 3940af1822de..368384b3e51c 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -63,6 +63,9 @@ export type {Context} from './types'; const esmIsAvailable = typeof SourceTextModule === 'function'; +const dataURIregex = + /^data:(?text\/javascript|application\/json|application\/wasm)(?:;(?charset=utf-8|base64))?,(?.*)$/; + interface JestGlobals extends Global.TestFrameworkGlobals { expect: typeof JestGlobals.expect; } @@ -553,6 +556,86 @@ export default class Runtime { return globals; } + if (specifier.startsWith('data:')) { + if ( + this._shouldMock( + referencingIdentifier, + specifier, + this._explicitShouldMockModule, + {conditions: this.esmConditions}, + ) + ) { + return this.importMock(referencingIdentifier, specifier, context); + } + + const fromCache = this._esmoduleRegistry.get(specifier); + + if (fromCache) { + return fromCache; + } + + const match = specifier.match(dataURIregex); + + if (!match || !match.groups) { + throw new Error('Invalid data URI'); + } + + const mime = match.groups.mime; + if (mime === 'application/wasm') { + throw new Error('WASM is currently not supported'); + } + + const encoding = match.groups.encoding; + let code = match.groups.code; + if (!encoding || encoding === 'charset=utf-8') { + code = decodeURIComponent(code); + } else if (encoding === 'base64') { + code = Buffer.from(code, 'base64').toString(); + } else { + throw new Error(`Invalid data URI encoding: ${encoding}`); + } + + let module; + if (mime === 'application/json') { + module = new SyntheticModule( + ['default'], + function () { + const obj = JSON.parse(code); + // @ts-expect-error: TS doesn't know what `this` is + this.setExport('default', obj); + }, + {context, identifier: specifier}, + ); + } else { + module = new SourceTextModule(code, { + context, + identifier: specifier, + importModuleDynamically: async ( + specifier: string, + referencingModule: VMModule, + ) => { + invariant( + runtimeSupportsVmModules, + 'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules', + ); + const module = await this.resolveModule( + specifier, + referencingModule.identifier, + referencingModule.context, + ); + + return this.linkAndEvaluateModule(module); + }, + initializeImportMeta(meta: ImportMeta) { + meta.url = specifier; + }, + }); + } + + this._esmoduleRegistry.set(specifier, module); + return module; + } + if (specifier.startsWith('file://')) { specifier = fileURLToPath(specifier); } From 6094810c9d571686447c2320ba8c150add414e1b Mon Sep 17 00:00:00 2001 From: Ryan Wilson-Perkin Date: Wed, 16 Feb 2022 04:29:09 -0500 Subject: [PATCH 3/6] fix: handle pretty formatting of wide arrays and array-like objects (#12402) --- CHANGELOG.md | 2 + .../src/__tests__/index.test.ts | 17 ++++++ packages/jest-matcher-utils/src/index.ts | 18 +++++-- packages/jest-schemas/src/index.ts | 1 + packages/pretty-format/README.md | 1 + .../src/__tests__/prettyFormat.test.ts | 53 +++++++++++++++++++ packages/pretty-format/src/collections.ts | 27 ++++++++-- packages/pretty-format/src/index.ts | 53 ++++++------------- packages/pretty-format/src/types.ts | 1 + 9 files changed, 128 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 877a2233c742..407ebae86ebd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - `[jest-resolve, jest-runtime]` Add support for `data:` URI import and mock ([#12392](https://github.com/facebook/jest/pull/12392)) - `[@jes/schemas]` New module for JSON schemas for Jest's config ([#12384](https://github.com/facebook/jest/pull/12384)) - `[jest-worker]` [**BREAKING**] Allow only absolute `workerPath` ([#12343](https://github.com/facebook/jest/pull/12343)) +- `[pretty-format]` New `maxWidth` parameter ([#12402](https://github.com/facebook/jest/pull/12402)) ### Fixes @@ -23,6 +24,7 @@ - `[jest-config]` Pass `moduleTypes` to `ts-node` to enforce CJS when transpiling ([#12397](https://github.com/facebook/jest/pull/12397)) - `[jest-environment-jsdom]` Make `jsdom` accessible to extending environments again ([#12232](https://github.com/facebook/jest/pull/12232)) - `[jest-jasmine2, jest-types]` [**BREAKING**] Move all `jasmine` specific types from `@jest/types` to its own package ([#12125](https://github.com/facebook/jest/pull/12125)) +- `[jest-matcher-utils]` Pass maxWidth to `pretty-format` to avoid printing every element in arrays by default ([#12402](https://github.com/facebook/jest/pull/12402)) ### Chore & Maintenance diff --git a/packages/jest-matcher-utils/src/__tests__/index.test.ts b/packages/jest-matcher-utils/src/__tests__/index.test.ts index 9ed9cc9e17e3..37fb9fafc130 100644 --- a/packages/jest-matcher-utils/src/__tests__/index.test.ts +++ b/packages/jest-matcher-utils/src/__tests__/index.test.ts @@ -97,6 +97,23 @@ describe('stringify()', () => { expect(stringify(big)).toBe(prettyFormat(big, {maxDepth: 1, min: true})); expect(stringify(small)).toBe(prettyFormat(small, {min: true})); }); + + test('reduces maxWidth if stringifying very large arrays', () => { + const big: any = []; + const small: any = []; + const testString = Array(1000).join('x'); + + for (let i = 0; i < 100; i += 1) { + big[i] = testString; + } + + for (let i = 0; i < 3; i += 1) { + small[i] = testString; + } + + expect(stringify(big)).toBe(prettyFormat(big, {maxWidth: 5, min: true})); + expect(stringify(small)).toBe(prettyFormat(small, {min: true})); + }); }); describe('ensureNumbers()', () => { diff --git a/packages/jest-matcher-utils/src/index.ts b/packages/jest-matcher-utils/src/index.ts index 7210d37c624c..cdbad1a6c79f 100644 --- a/packages/jest-matcher-utils/src/index.ts +++ b/packages/jest-matcher-utils/src/index.ts @@ -89,13 +89,18 @@ export const SUGGEST_TO_CONTAIN_EQUAL = chalk.dim( 'Looks like you wanted to test for object/array equality with the stricter `toContain` matcher. You probably need to use `toContainEqual` instead.', ); -export const stringify = (object: unknown, maxDepth: number = 10): string => { +export const stringify = ( + object: unknown, + maxDepth: number = 10, + maxWidth: number = 10, +): string => { const MAX_LENGTH = 10000; let result; try { result = prettyFormat(object, { maxDepth, + maxWidth, min: true, plugins: PLUGINS, }); @@ -103,14 +108,19 @@ export const stringify = (object: unknown, maxDepth: number = 10): string => { result = prettyFormat(object, { callToJSON: false, maxDepth, + maxWidth, min: true, plugins: PLUGINS, }); } - return result.length >= MAX_LENGTH && maxDepth > 1 - ? stringify(object, Math.floor(maxDepth / 2)) - : result; + if (result.length >= MAX_LENGTH && maxDepth > 1) { + return stringify(object, Math.floor(maxDepth / 2), maxWidth); + } else if (result.length >= MAX_LENGTH && maxWidth > 1) { + return stringify(object, maxDepth, Math.floor(maxWidth / 2)); + } else { + return result; + } }; export const highlightTrailingWhitespace = (text: string): string => diff --git a/packages/jest-schemas/src/index.ts b/packages/jest-schemas/src/index.ts index b3f0a32eebe8..d0f6f4010165 100644 --- a/packages/jest-schemas/src/index.ts +++ b/packages/jest-schemas/src/index.ts @@ -15,6 +15,7 @@ const RawSnapshotFormat = Type.Partial( highlight: Type.Readonly(Type.Boolean()), indent: Type.Readonly(Type.Number({minimum: 0})), maxDepth: Type.Readonly(Type.Number({minimum: 0})), + maxWidth: Type.Readonly(Type.Number({minimum: 0})), min: Type.Readonly(Type.Boolean()), printBasicPrototype: Type.Readonly(Type.Boolean()), printFunctionName: Type.Readonly(Type.Boolean()), diff --git a/packages/pretty-format/README.md b/packages/pretty-format/README.md index c5cb0041dbfa..3dae52a159fe 100755 --- a/packages/pretty-format/README.md +++ b/packages/pretty-format/README.md @@ -75,6 +75,7 @@ console.log(prettyFormat(onClick, options)); | `highlight` | `boolean` | `false` | highlight syntax with colors in terminal (some plugins) | | `indent` | `number` | `2` | spaces in each level of indentation | | `maxDepth` | `number` | `Infinity` | levels to print in arrays, objects, elements, and so on | +| `maxWidth` | `number` | `Infinity` | number of elements to print in arrays, sets, and so on | | `min` | `boolean` | `false` | minimize added space: no indentation nor line breaks | | `plugins` | `array` | `[]` | plugins to serialize application-specific data types | | `printBasicPrototype` | `boolean` | `false` | print the prototype for plain objects and arrays | diff --git a/packages/pretty-format/src/__tests__/prettyFormat.test.ts b/packages/pretty-format/src/__tests__/prettyFormat.test.ts index ab9d0b9da214..73b9237d54b6 100644 --- a/packages/pretty-format/src/__tests__/prettyFormat.test.ts +++ b/packages/pretty-format/src/__tests__/prettyFormat.test.ts @@ -562,6 +562,59 @@ describe('prettyFormat()', () => { ); }); + describe('maxWidth option', () => { + it('applies to arrays', () => { + const val = Array(1_000_000).fill('x'); + expect(prettyFormat(val, {maxWidth: 5})).toEqual( + [ + 'Array [', + ' "x",', + ' "x",', + ' "x",', + ' "x",', + ' "x",', + ' …', + ']', + ].join('\n'), + ); + }); + + it('applies to sets', () => { + const val = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); + expect(prettyFormat(val, {maxWidth: 5})).toEqual( + ['Set {', ' 1,', ' 2,', ' 3,', ' 4,', ' 5,', ' …', '}'].join( + '\n', + ), + ); + }); + + it('applies to maps', () => { + const val = new Map(); + val.set('a', 1); + val.set('b', 2); + val.set('c', 3); + val.set('d', 4); + val.set('e', 5); + val.set('f', 6); + val.set('g', 7); + val.set('h', 8); + val.set('i', 9); + val.set('j', 10); + expect(prettyFormat(val, {maxWidth: 5})).toEqual( + [ + 'Map {', + ' "a" => 1,', + ' "b" => 2,', + ' "c" => 3,', + ' "d" => 4,', + ' "e" => 5,', + ' …', + '}', + ].join('\n'), + ); + }); + }); + it('can customize the max depth', () => { const val = [ { diff --git a/packages/pretty-format/src/collections.ts b/packages/pretty-format/src/collections.ts index 97fae10163ba..0495f35be557 100644 --- a/packages/pretty-format/src/collections.ts +++ b/packages/pretty-format/src/collections.ts @@ -43,6 +43,7 @@ export function printIteratorEntries( separator: string = ': ', ): string { let result = ''; + let width = 0; let current = iterator.next(); if (!current.done) { @@ -51,6 +52,13 @@ export function printIteratorEntries( const indentationNext = indentation + config.indent; while (!current.done) { + result += indentationNext; + + if (width++ === config.maxWidth) { + result += '…'; + break; + } + const name = printer( current.value[0], config, @@ -66,7 +74,7 @@ export function printIteratorEntries( refs, ); - result += indentationNext + name + separator + value; + result += name + separator + value; current = iterator.next(); @@ -97,6 +105,7 @@ export function printIteratorValues( printer: Printer, ): string { let result = ''; + let width = 0; let current = iterator.next(); if (!current.done) { @@ -105,9 +114,14 @@ export function printIteratorValues( const indentationNext = indentation + config.indent; while (!current.done) { - result += - indentationNext + - printer(current.value, config, indentationNext, depth, refs); + result += indentationNext; + + if (width++ === config.maxWidth) { + result += '…'; + break; + } + + result += printer(current.value, config, indentationNext, depth, refs); current = iterator.next(); @@ -147,6 +161,11 @@ export function printListItems( for (let i = 0; i < list.length; i++) { result += indentationNext; + if (i === config.maxWidth) { + result += '…'; + break; + } + if (i in list) { result += printer(list[i], config, indentationNext, depth, refs); } diff --git a/packages/pretty-format/src/index.ts b/packages/pretty-format/src/index.ts index 9543e6b354a8..3d9d4ce90564 100644 --- a/packages/pretty-format/src/index.ts +++ b/packages/pretty-format/src/index.ts @@ -404,6 +404,7 @@ export const DEFAULT_OPTIONS: Options = { highlight: false, indent: 2, maxDepth: Infinity, + maxWidth: Infinity, min: false, plugins: [], printBasicPrototype: true, @@ -465,56 +466,34 @@ const getColorsEmpty = (): Colors => }, Object.create(null)); const getPrintFunctionName = (options?: OptionsReceived) => - options && options.printFunctionName !== undefined - ? options.printFunctionName - : DEFAULT_OPTIONS.printFunctionName; + options?.printFunctionName ?? DEFAULT_OPTIONS.printFunctionName; const getEscapeRegex = (options?: OptionsReceived) => - options && options.escapeRegex !== undefined - ? options.escapeRegex - : DEFAULT_OPTIONS.escapeRegex; + options?.escapeRegex ?? DEFAULT_OPTIONS.escapeRegex; const getEscapeString = (options?: OptionsReceived) => - options && options.escapeString !== undefined - ? options.escapeString - : DEFAULT_OPTIONS.escapeString; + options?.escapeString ?? DEFAULT_OPTIONS.escapeString; const getConfig = (options?: OptionsReceived): Config => ({ - callToJSON: - options && options.callToJSON !== undefined - ? options.callToJSON - : DEFAULT_OPTIONS.callToJSON, - colors: - options && options.highlight - ? getColorsHighlight(options) - : getColorsEmpty(), + callToJSON: options?.callToJSON ?? DEFAULT_OPTIONS.callToJSON, + colors: options?.highlight ? getColorsHighlight(options) : getColorsEmpty(), compareKeys: - options && typeof options.compareKeys === 'function' + typeof options?.compareKeys === 'function' ? options.compareKeys : DEFAULT_OPTIONS.compareKeys, escapeRegex: getEscapeRegex(options), escapeString: getEscapeString(options), - indent: - options && options.min - ? '' - : createIndent( - options && options.indent !== undefined - ? options.indent - : DEFAULT_OPTIONS.indent, - ), - maxDepth: - options && options.maxDepth !== undefined - ? options.maxDepth - : DEFAULT_OPTIONS.maxDepth, - min: options && options.min !== undefined ? options.min : DEFAULT_OPTIONS.min, - plugins: - options && options.plugins !== undefined - ? options.plugins - : DEFAULT_OPTIONS.plugins, + indent: options?.min + ? '' + : createIndent(options?.indent ?? DEFAULT_OPTIONS.indent), + maxDepth: options?.maxDepth ?? DEFAULT_OPTIONS.maxDepth, + maxWidth: options?.maxWidth ?? DEFAULT_OPTIONS.maxWidth, + min: options?.min ?? DEFAULT_OPTIONS.min, + plugins: options?.plugins ?? DEFAULT_OPTIONS.plugins, printBasicPrototype: options?.printBasicPrototype ?? true, printFunctionName: getPrintFunctionName(options), - spacingInner: options && options.min ? ' ' : '\n', - spacingOuter: options && options.min ? '' : '\n', + spacingInner: options?.min ? ' ' : '\n', + spacingOuter: options?.min ? '' : '\n', }); function createIndent(indent: number): string { diff --git a/packages/pretty-format/src/types.ts b/packages/pretty-format/src/types.ts index c26b77aee0f7..62e9a0b917ff 100644 --- a/packages/pretty-format/src/types.ts +++ b/packages/pretty-format/src/types.ts @@ -45,6 +45,7 @@ export type Config = { escapeString: boolean; indent: string; maxDepth: number; + maxWidth: number; min: boolean; plugins: Plugins; printBasicPrototype: boolean; From 943d8234f3aad2a8e282569e7f52b6e11f917a43 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Wed, 16 Feb 2022 11:21:30 +0100 Subject: [PATCH 4/6] chore: correct typo in changelog --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 407ebae86ebd..ffaf4110ea52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ - `[@jest/expect-utils]` New module exporting utils for `expect` ([#12323](https://github.com/facebook/jest/pull/12323)) - `[jest-resolver]` [**BREAKING**] Add support for `package.json` `exports` ([11961](https://github.com/facebook/jest/pull/11961)) - `[jest-resolve, jest-runtime]` Add support for `data:` URI import and mock ([#12392](https://github.com/facebook/jest/pull/12392)) -- `[@jes/schemas]` New module for JSON schemas for Jest's config ([#12384](https://github.com/facebook/jest/pull/12384)) +- `[@jest/schemas]` New module for JSON schemas for Jest's config ([#12384](https://github.com/facebook/jest/pull/12384)) - `[jest-worker]` [**BREAKING**] Allow only absolute `workerPath` ([#12343](https://github.com/facebook/jest/pull/12343)) - `[pretty-format]` New `maxWidth` parameter ([#12402](https://github.com/facebook/jest/pull/12402)) @@ -31,6 +31,7 @@ - `[*]` [**BREAKING**] Drop support for Node v10 and v15 and target first LTS `16.13.0` ([#12220](https://github.com/facebook/jest/pull/12220)) - `[*]` [**BREAKING**] Drop support for `typescript@3.8`, minimum version is now `4.2` ([#11142](https://github.com/facebook/jest/pull/11142)) - `[*]` Bundle all `.d.ts` files into a single `index.d.ts` per module ([#12345](https://github.com/facebook/jest/pull/12345)) +- `[docs]` Add note about not mixing `done()` with Promises ([#11077](https://github.com/facebook/jest/pull/11077)) - `[docs, examples]` Update React examples to match with the new React guidelines for code examples ([#12217](https://github.com/facebook/jest/pull/12217)) - `[expect]` [**BREAKING**] Remove support for importing `build/utils` ([#12323](https://github.com/facebook/jest/pull/12323)) - `[expect]` [**BREAKING**] Migrate to ESM ([#12344](https://github.com/facebook/jest/pull/12344)) @@ -48,7 +49,6 @@ - `[jest-snapshot]` [**BREAKING**] Migrate to ESM ([#12342](https://github.com/facebook/jest/pull/12342)) - `[jest-transform]` Update `write-file-atomic` to v4 ([#12357](https://github.com/facebook/jest/pull/12357)) - `[jest]` Use `index.ts` instead of `jest.ts` as main export ([#12329](https://github.com/facebook/jest/pull/12329)) -- `[docs]` Add note about not mixing `done()` with Promises ([#11077](https://github.com/facebook/jest/pull/11077)) ### Performance From 4f4538c5534b27decfc83031638de72305271391 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Wed, 16 Feb 2022 12:26:08 +0100 Subject: [PATCH 5/6] chore: type printWithType more accurately (#12405) --- packages/jest-matcher-utils/src/index.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/jest-matcher-utils/src/index.ts b/packages/jest-matcher-utils/src/index.ts index cdbad1a6c79f..eb62f5197c26 100644 --- a/packages/jest-matcher-utils/src/index.ts +++ b/packages/jest-matcher-utils/src/index.ts @@ -136,11 +136,11 @@ export const printReceived = (object: unknown): string => export const printExpected = (value: unknown): string => EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); -export const printWithType = ( - name: string, // 'Expected' or 'Received' - value: unknown, - print: (value: unknown) => string, // printExpected or printReceived -): string => { +export function printWithType( + name: string, + value: T, + print: (value: T) => string, +): string { const type = getType(value); const hasType = type !== 'null' && type !== 'undefined' @@ -148,7 +148,7 @@ export const printWithType = ( : ''; const hasValue = `${name} has value: ${print(value)}`; return hasType + hasValue; -}; +} export const ensureNoExpected = ( expected: unknown, @@ -511,8 +511,8 @@ export const matcherErrorMessage = ( // Old format: matcher name has dim color export const matcherHint = ( matcherName: string, - received: string = 'received', - expected: string = 'expected', + received = 'received', + expected = 'expected', options: MatcherHintOptions = {}, ): string => { const { From 199f9811ae68b15879cbe18b7ef7ebd61eefcf23 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Wed, 16 Feb 2022 12:26:28 +0100 Subject: [PATCH 6/6] chore: remove `Path` and `Glob` (#12406) --- CHANGELOG.md | 1 + e2e/Utils.ts | 11 +- packages/babel-jest/package.json | 1 - packages/babel-jest/src/index.ts | 25 ++-- packages/babel-jest/tsconfig.json | 6 +- packages/expect/package.json | 1 - packages/expect/src/types.ts | 3 +- packages/expect/tsconfig.json | 1 - packages/jest-changed-files/package.json | 1 - packages/jest-changed-files/src/git.ts | 5 +- packages/jest-changed-files/src/index.ts | 5 +- packages/jest-changed-files/src/types.ts | 13 +-- packages/jest-changed-files/tsconfig.json | 3 +- .../jestAdapterInit.ts | 4 +- packages/jest-cli/src/cli/index.ts | 7 +- packages/jest-config/src/getCacheDirectory.ts | 3 +- packages/jest-config/src/index.ts | 10 +- packages/jest-config/src/normalize.ts | 10 +- .../src/readConfigFileAndSetRootDir.ts | 4 +- packages/jest-config/src/resolveConfigPath.ts | 30 +++-- packages/jest-config/src/utils.ts | 19 ++- packages/jest-core/src/SearchSource.ts | 16 +-- packages/jest-core/src/TestScheduler.ts | 4 +- .../src/__tests__/SearchSource.test.ts | 2 +- packages/jest-core/src/cli/index.ts | 2 +- .../jest-core/src/getChangedFilesPromise.ts | 2 +- packages/jest-core/src/lib/isValidPath.ts | 2 +- packages/jest-core/src/types.ts | 5 +- .../src/index.ts | 4 +- packages/jest-environment/src/index.ts | 2 +- packages/jest-haste-map/src/HasteFS.ts | 30 +++-- packages/jest-haste-map/src/ModuleMap.ts | 9 +- .../jest-haste-map/src/crawlers/watchman.ts | 3 +- packages/jest-haste-map/src/index.ts | 14 +-- packages/jest-haste-map/src/types.ts | 25 ++-- packages/jest-jasmine2/src/index.ts | 1 + packages/jest-jasmine2/src/jasmine/Spec.ts | 5 +- packages/jest-jasmine2/src/jasmine/Suite.ts | 5 +- packages/jest-jasmine2/src/reporter.ts | 4 +- .../jest-jasmine2/src/setup_jest_globals.ts | 2 +- packages/jest-jasmine2/src/types.ts | 3 +- packages/jest-message-util/src/index.ts | 10 +- packages/jest-reporters/src/CoverageWorker.ts | 2 +- .../jest-reporters/src/DefaultReporter.ts | 4 +- packages/jest-reporters/src/Status.ts | 8 +- .../src/generateEmptyCoverage.ts | 6 +- packages/jest-reporters/src/types.ts | 12 +- packages/jest-reporters/src/utils.ts | 6 +- .../jest-resolve-dependencies/package.json | 2 +- .../src/__tests__/dependency_resolver.test.ts | 2 +- .../jest-resolve-dependencies/src/index.ts | 32 +++--- packages/jest-resolve/package.json | 1 - .../jest-resolve/src/ModuleNotFoundError.ts | 5 +- packages/jest-resolve/src/defaultResolver.ts | 19 ++- packages/jest-resolve/src/fileWalkers.ts | 15 +-- packages/jest-resolve/src/nodeModulesPaths.ts | 11 +- packages/jest-resolve/src/resolver.ts | 61 +++++----- packages/jest-resolve/src/shouldLoadAsEsm.ts | 11 +- packages/jest-resolve/src/types.ts | 8 +- packages/jest-resolve/src/utils.ts | 16 +-- packages/jest-resolve/tsconfig.json | 1 - packages/jest-runner/src/runTest.ts | 4 +- packages/jest-runner/src/testWorker.ts | 2 +- packages/jest-runner/src/types.ts | 8 +- packages/jest-runtime/src/helpers.ts | 2 +- packages/jest-runtime/src/index.ts | 58 +++++----- packages/jest-serializer/src/index.ts | 6 +- packages/jest-snapshot/src/InlineSnapshots.ts | 7 +- .../jest-snapshot/src/SnapshotResolver.ts | 18 +-- packages/jest-snapshot/src/State.ts | 8 +- packages/jest-snapshot/src/index.ts | 6 +- packages/jest-snapshot/src/utils.ts | 8 +- packages/jest-test-result/src/helpers.ts | 3 +- packages/jest-test-result/src/types.ts | 6 +- .../jest-transform/src/ScriptTransformer.ts | 62 +++++----- .../src/__tests__/ScriptTransformer.test.ts | 4 +- .../jest-transform/src/shouldInstrument.ts | 2 +- packages/jest-transform/src/types.ts | 20 ++-- packages/jest-types/src/Config.ts | 108 +++++++++--------- packages/jest-util/src/createDirectory.ts | 3 +- packages/jest-util/src/globsToMatcher.ts | 5 +- .../jest-util/src/replacePathSepForGlob.ts | 4 +- .../jest-util/src/requireOrImportModule.ts | 3 +- packages/jest-util/src/tryRealpath.ts | 3 +- packages/jest-watcher/src/types.ts | 2 +- yarn.lock | 4 - 86 files changed, 401 insertions(+), 490 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffaf4110ea52..ce1923b04bec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,7 @@ - `[jest-serializer]` [**BREAKING**] Deprecate package in favour of using `v8` APIs directly ([#12391](https://github.com/facebook/jest/pull/12391)) - `[jest-snapshot]` [**BREAKING**] Migrate to ESM ([#12342](https://github.com/facebook/jest/pull/12342)) - `[jest-transform]` Update `write-file-atomic` to v4 ([#12357](https://github.com/facebook/jest/pull/12357)) +- `[jest-types]` [**BREAKING**] Remove `Config.Glob` and `Config.Path` ([#12406](https://github.com/facebook/jest/pull/12406)) - `[jest]` Use `index.ts` instead of `jest.ts` as main export ([#12329](https://github.com/facebook/jest/pull/12329)) ### Performance diff --git a/e2e/Utils.ts b/e2e/Utils.ts index e5b44d1a74ca..f738bf63dfc7 100644 --- a/e2e/Utils.ts +++ b/e2e/Utils.ts @@ -20,7 +20,7 @@ interface RunResult extends ExecaReturnValue { } export const run = ( cmd: string, - cwd?: Config.Path, + cwd?: string, env?: Record, ): RunResult => { const args = cmd.split(/\s/).slice(1); @@ -44,10 +44,7 @@ export const run = ( return result; }; -export const runYarnInstall = ( - cwd: Config.Path, - env?: Record, -) => { +export const runYarnInstall = (cwd: string, env?: Record) => { const lockfilePath = path.resolve(cwd, 'yarn.lock'); let exists = true; @@ -60,7 +57,7 @@ export const runYarnInstall = ( return run(exists ? 'yarn install --immutable' : 'yarn install', cwd, env); }; -export const linkJestPackage = (packageName: string, cwd: Config.Path) => { +export const linkJestPackage = (packageName: string, cwd: string) => { const packagesDir = path.resolve(__dirname, '../packages'); const packagePath = path.resolve(packagesDir, packageName); const destination = path.resolve(cwd, 'node_modules/', packageName); @@ -182,7 +179,7 @@ const DEFAULT_PACKAGE_JSON: JestPackageJson = { }; export const createEmptyPackage = ( - directory: Config.Path, + directory: string, packageJson: PackageJson = DEFAULT_PACKAGE_JSON, ) => { const packageJsonWithDefaults = { diff --git a/packages/babel-jest/package.json b/packages/babel-jest/package.json index 74325351b4dc..27ab90b48d5f 100644 --- a/packages/babel-jest/package.json +++ b/packages/babel-jest/package.json @@ -19,7 +19,6 @@ }, "dependencies": { "@jest/transform": "^28.0.0-alpha.1", - "@jest/types": "^28.0.0-alpha.1", "@types/babel__core": "^7.1.14", "babel-plugin-istanbul": "^6.1.1", "babel-preset-jest": "^28.0.0-alpha.0", diff --git a/packages/babel-jest/src/index.ts b/packages/babel-jest/src/index.ts index d968c0ff939c..522d5cc58390 100644 --- a/packages/babel-jest/src/index.ts +++ b/packages/babel-jest/src/index.ts @@ -20,7 +20,6 @@ import type { TransformOptions as JestTransformOptions, SyncTransformer, } from '@jest/transform'; -import type {Config} from '@jest/types'; import {loadPartialConfig, loadPartialConfigAsync} from './loadBabelConfig'; const THIS_FILE = fs.readFileSync(__filename); @@ -31,8 +30,8 @@ type CreateTransformer = SyncTransformer['createTransformer']; function assertLoadedBabelConfig( babelConfig: Readonly | null, - cwd: Config.Path, - filename: Config.Path, + cwd: string, + filename: string, ): asserts babelConfig { if (!babelConfig) { throw new Error( @@ -72,7 +71,7 @@ function addIstanbulInstrumentation( function getCacheKeyFromConfig( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, babelOptions: PartialConfig, transformOptions: JestTransformOptions, ): string { @@ -104,8 +103,8 @@ function getCacheKeyFromConfig( } function loadBabelConfig( - cwd: Config.Path, - filename: Config.Path, + cwd: string, + filename: string, transformOptions: TransformOptions, ): PartialConfig { const babelConfig = loadPartialConfig(transformOptions); @@ -116,8 +115,8 @@ function loadBabelConfig( } async function loadBabelConfigAsync( - cwd: Config.Path, - filename: Config.Path, + cwd: string, + filename: string, transformOptions: TransformOptions, ): Promise { const babelConfig = await loadPartialConfigAsync(transformOptions); @@ -128,8 +127,8 @@ async function loadBabelConfigAsync( } function loadBabelOptions( - cwd: Config.Path, - filename: Config.Path, + cwd: string, + filename: string, transformOptions: TransformOptions, jestTransformOptions: JestTransformOptions, ): TransformOptions { @@ -139,8 +138,8 @@ function loadBabelOptions( } async function loadBabelOptionsAsync( - cwd: Config.Path, - filename: Config.Path, + cwd: string, + filename: string, transformOptions: TransformOptions, jestTransformOptions: JestTransformOptions, ): Promise { @@ -169,7 +168,7 @@ export const createTransformer: CreateTransformer = userOptions => { } as const; function mergeBabelTransformOptions( - filename: Config.Path, + filename: string, transformOptions: JestTransformOptions, ): TransformOptions { const {cwd} = transformOptions.config; diff --git a/packages/babel-jest/tsconfig.json b/packages/babel-jest/tsconfig.json index 1ffeba9a4488..a58a0880e8aa 100644 --- a/packages/babel-jest/tsconfig.json +++ b/packages/babel-jest/tsconfig.json @@ -7,9 +7,5 @@ "include": ["./src/**/*"], "exclude": ["./**/__tests__/**/*"], // TODO: include `babel-preset-jest` if it's ever in TS even though we don't care about its types - "references": [ - {"path": "../jest-transform"}, - {"path": "../jest-types"}, - {"path": "../test-utils"} - ] + "references": [{"path": "../jest-transform"}, {"path": "../test-utils"}] } diff --git a/packages/expect/package.json b/packages/expect/package.json index 4564def15cae..0f4990e95756 100644 --- a/packages/expect/package.json +++ b/packages/expect/package.json @@ -19,7 +19,6 @@ }, "dependencies": { "@jest/expect-utils": "^28.0.0-alpha.1", - "@jest/types": "^28.0.0-alpha.1", "jest-get-type": "^28.0.0-alpha.0", "jest-matcher-utils": "^28.0.0-alpha.1", "jest-message-util": "^28.0.0-alpha.1" diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 94a03e70f127..486b3a8a4f07 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -7,7 +7,6 @@ */ import type {EqualsFunction, Tester} from '@jest/expect-utils'; -import type {Config} from '@jest/types'; import type * as jestMatcherUtils from 'jest-matcher-utils'; import {INTERNAL_MATCHER_FLAG} from './jestMatchersObject'; @@ -56,7 +55,7 @@ export interface MatcherState { isNot: boolean; promise: string; suppressedErrors: Array; - testPath?: Config.Path; + testPath?: string; utils: typeof jestMatcherUtils & { iterableEquality: Tester; subsetEquality: Tester; diff --git a/packages/expect/tsconfig.json b/packages/expect/tsconfig.json index 3609d0f6e862..9c5b8e7c5117 100644 --- a/packages/expect/tsconfig.json +++ b/packages/expect/tsconfig.json @@ -11,7 +11,6 @@ {"path": "../jest-get-type"}, {"path": "../jest-matcher-utils"}, {"path": "../jest-message-util"}, - {"path": "../jest-types"}, {"path": "../test-utils"} ] } diff --git a/packages/jest-changed-files/package.json b/packages/jest-changed-files/package.json index 259b2b08200c..7b3c8b2ef75f 100644 --- a/packages/jest-changed-files/package.json +++ b/packages/jest-changed-files/package.json @@ -17,7 +17,6 @@ "./package.json": "./package.json" }, "dependencies": { - "@jest/types": "^28.0.0-alpha.1", "execa": "^5.0.0", "throat": "^6.0.1" }, diff --git a/packages/jest-changed-files/src/git.ts b/packages/jest-changed-files/src/git.ts index c868e9fa002e..1cd4ee311fa7 100644 --- a/packages/jest-changed-files/src/git.ts +++ b/packages/jest-changed-files/src/git.ts @@ -8,13 +8,12 @@ import * as path from 'path'; import execa = require('execa'); -import type {Config} from '@jest/types'; import type {SCMAdapter} from './types'; const findChangedFilesUsingCommand = async ( args: Array, - cwd: Config.Path, -): Promise> => { + cwd: string, +): Promise> => { let result: execa.ExecaReturnValue; try { diff --git a/packages/jest-changed-files/src/index.ts b/packages/jest-changed-files/src/index.ts index 69ddb8ce3b11..96ec1bf80d5a 100644 --- a/packages/jest-changed-files/src/index.ts +++ b/packages/jest-changed-files/src/index.ts @@ -7,7 +7,6 @@ */ import throat from 'throat'; -import type {Config} from '@jest/types'; import git from './git'; import hg from './hg'; import type {ChangedFilesPromise, Options, Repos, SCMAdapter} from './types'; @@ -28,7 +27,7 @@ const findGitRoot = (dir: string) => mutex(() => git.getRoot(dir)); const findHgRoot = (dir: string) => mutex(() => hg.getRoot(dir)); export const getChangedFilesForRoots = async ( - roots: Array, + roots: Array, options: Options, ): ChangedFilesPromise => { const repos = await findRepos(roots); @@ -56,7 +55,7 @@ export const getChangedFilesForRoots = async ( return {changedFiles, repos}; }; -export const findRepos = async (roots: Array): Promise => { +export const findRepos = async (roots: Array): Promise => { const gitRepos = await Promise.all( roots.reduce>( (promises, root) => promises.concat(findGitRoot(root)), diff --git a/packages/jest-changed-files/src/types.ts b/packages/jest-changed-files/src/types.ts index a7873ac8cee0..f320b7a89563 100644 --- a/packages/jest-changed-files/src/types.ts +++ b/packages/jest-changed-files/src/types.ts @@ -5,24 +5,19 @@ * LICENSE file in the root directory of this source tree. */ -import type {Config} from '@jest/types'; - export type Options = { lastCommit?: boolean; withAncestor?: boolean; changedSince?: string; - includePaths?: Array; + includePaths?: Array; }; -type Paths = Set; +type Paths = Set; export type Repos = {git: Paths; hg: Paths}; export type ChangedFiles = {repos: Repos; changedFiles: Paths}; export type ChangedFilesPromise = Promise; export type SCMAdapter = { - findChangedFiles: ( - cwd: Config.Path, - options: Options, - ) => Promise>; - getRoot: (cwd: Config.Path) => Promise; + findChangedFiles: (cwd: string, options: Options) => Promise>; + getRoot: (cwd: string) => Promise; }; diff --git a/packages/jest-changed-files/tsconfig.json b/packages/jest-changed-files/tsconfig.json index 4003592c4d85..12688a2879d6 100644 --- a/packages/jest-changed-files/tsconfig.json +++ b/packages/jest-changed-files/tsconfig.json @@ -4,6 +4,5 @@ "rootDir": "src", "outDir": "build" }, - "include": ["./src/**/*"], - "references": [{"path": "../jest-types"}] + "include": ["./src/**/*"] } diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts index 6e4e01f7da2c..f7698576c396 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts @@ -54,8 +54,8 @@ export const initialize = async ({ config: Config.ProjectConfig; environment: JestEnvironment; globalConfig: Config.GlobalConfig; - localRequire: (path: Config.Path) => T; - testPath: Config.Path; + localRequire: (path: string) => T; + testPath: string; parentProcess: Process; sendMessageToJest?: TestFileEvent; setGlobalsForRuntime: (globals: JestGlobals) => void; diff --git a/packages/jest-cli/src/cli/index.ts b/packages/jest-cli/src/cli/index.ts index 4296338430de..508059cd588b 100644 --- a/packages/jest-cli/src/cli/index.ts +++ b/packages/jest-cli/src/cli/index.ts @@ -20,7 +20,7 @@ import * as args from './args'; export async function run( maybeArgv?: Array, - project?: Config.Path, + project?: string, ): Promise { try { const argv = await buildArgv(maybeArgv); @@ -85,10 +85,7 @@ export async function buildArgv( ); } -const getProjectListFromCLIArgs = ( - argv: Config.Argv, - project?: Config.Path, -) => { +const getProjectListFromCLIArgs = (argv: Config.Argv, project?: string) => { const projects = argv.projects ? argv.projects : []; if (project) { diff --git a/packages/jest-config/src/getCacheDirectory.ts b/packages/jest-config/src/getCacheDirectory.ts index 12944ccff4a8..fca2f838d04b 100644 --- a/packages/jest-config/src/getCacheDirectory.ts +++ b/packages/jest-config/src/getCacheDirectory.ts @@ -7,10 +7,9 @@ import {tmpdir} from 'os'; import * as path from 'path'; -import type {Config} from '@jest/types'; import {tryRealpath} from 'jest-util'; -const getCacheDirectory: () => Config.Path = () => { +const getCacheDirectory: () => string = () => { const {getuid} = process; const tmpdirPath = path.join(tryRealpath(tmpdir()), 'jest'); if (getuid == null) { diff --git a/packages/jest-config/src/index.ts b/packages/jest-config/src/index.ts index 5254186e48db..a1122db030cd 100644 --- a/packages/jest-config/src/index.ts +++ b/packages/jest-config/src/index.ts @@ -25,7 +25,7 @@ export {default as descriptions} from './Descriptions'; export {constants}; type ReadConfig = { - configPath: Config.Path | null | undefined; + configPath: string | null | undefined; globalConfig: Config.GlobalConfig; hasDeprecationWarnings: boolean; projectConfig: Config.ProjectConfig; @@ -33,13 +33,13 @@ type ReadConfig = { export async function readConfig( argv: Config.Argv, - packageRootOrConfig: Config.Path | Config.InitialOptions, + packageRootOrConfig: string | Config.InitialOptions, // 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?: boolean, - parentConfigDirname?: Config.Path | null, + parentConfigDirname?: string | null, projectIndex = Infinity, skipMultipleConfigWarning = false, ): Promise { @@ -278,7 +278,7 @@ This usually means that your ${chalk.bold( // (and only) project. export async function readConfigs( argv: Config.Argv, - projectPaths: Array, + projectPaths: Array, ): Promise<{ globalConfig: Config.GlobalConfig; configs: Array; @@ -288,7 +288,7 @@ export async function readConfigs( let hasDeprecationWarnings; let configs: Array = []; let projects = projectPaths; - let configPath: Config.Path | null | undefined; + let configPath: string | null | undefined; if (projectPaths.length === 1) { const parsedConfig = await readConfig(argv, projects[0]); diff --git a/packages/jest-config/src/normalize.ts b/packages/jest-config/src/normalize.ts index 09574fe4d69d..c65dfb8abdd9 100644 --- a/packages/jest-config/src/normalize.ts +++ b/packages/jest-config/src/normalize.ts @@ -54,7 +54,7 @@ type AllOptions = Config.ProjectConfig & Config.GlobalConfig; const createConfigError = (message: string) => new ValidationError(ERROR, message, DOCUMENTATION_NOTE); -function verifyDirectoryExists(path: Config.Path, key: string) { +function verifyDirectoryExists(path: string, key: string) { try { const rootStat = statSync(path); @@ -257,7 +257,7 @@ const normalizeCollectCoverageOnlyFrom = ( key: keyof Pick, ) => { const initialCollectCoverageFrom = options[key]; - const collectCoverageOnlyFrom: Array = Array.isArray( + const collectCoverageOnlyFrom: Array = Array.isArray( initialCollectCoverageFrom, ) ? initialCollectCoverageFrom // passed from argv @@ -278,7 +278,7 @@ const normalizeCollectCoverageFrom = ( key: keyof Pick, ) => { const initialCollectCoverageFrom = options[key]; - let value: Array | undefined; + let value: Array | undefined; if (!initialCollectCoverageFrom) { value = []; } @@ -366,7 +366,7 @@ const normalizePreprocessor = ( const normalizeMissingOptions = ( options: Config.InitialOptionsWithRootDir, - configPath: Config.Path | null | undefined, + configPath: string | null | undefined, projectIndex: number, ): Config.InitialOptionsWithRootDir => { if (!options.name) { @@ -550,7 +550,7 @@ function validateExtensionsToTreatAsEsm( export default async function normalize( initialOptions: Config.InitialOptions, argv: Config.Argv, - configPath?: Config.Path | null, + configPath?: string | null, projectIndex = Infinity, ): Promise<{ hasDeprecationWarnings: boolean; diff --git a/packages/jest-config/src/readConfigFileAndSetRootDir.ts b/packages/jest-config/src/readConfigFileAndSetRootDir.ts index 000bed86e804..e4361c8c1f54 100644 --- a/packages/jest-config/src/readConfigFileAndSetRootDir.ts +++ b/packages/jest-config/src/readConfigFileAndSetRootDir.ts @@ -24,7 +24,7 @@ import { // 3. For any other file, we just require it. If we receive an 'ERR_REQUIRE_ESM' // from node, perform a dynamic import instead. export default async function readConfigFileAndSetRootDir( - configPath: Config.Path, + configPath: string, ): Promise { const isTS = configPath.endsWith(JEST_CONFIG_EXT_TS); const isJSON = configPath.endsWith(JEST_CONFIG_EXT_JSON); @@ -81,7 +81,7 @@ let registerer: Service; // Load the TypeScript configuration const loadTSConfigFile = async ( - configPath: Config.Path, + configPath: string, ): Promise => { // Register TypeScript compiler instance await registerTsNode(); diff --git a/packages/jest-config/src/resolveConfigPath.ts b/packages/jest-config/src/resolveConfigPath.ts index 0b36f252d50e..e513340fb5dd 100644 --- a/packages/jest-config/src/resolveConfigPath.ts +++ b/packages/jest-config/src/resolveConfigPath.ts @@ -9,23 +9,22 @@ import * as path from 'path'; import chalk = require('chalk'); import * as fs from 'graceful-fs'; import slash = require('slash'); -import type {Config} from '@jest/types'; import { JEST_CONFIG_BASE_NAME, JEST_CONFIG_EXT_ORDER, PACKAGE_JSON, } from './constants'; -const isFile = (filePath: Config.Path) => +const isFile = (filePath: string) => fs.existsSync(filePath) && !fs.lstatSync(filePath).isDirectory(); const getConfigFilename = (ext: string) => JEST_CONFIG_BASE_NAME + ext; export default function resolveConfigPath( - pathToResolve: Config.Path, - cwd: Config.Path, + pathToResolve: string, + cwd: string, skipMultipleConfigWarning = false, -): Config.Path { +): string { if (!path.isAbsolute(cwd)) { throw new Error(`"cwd" must be an absolute path. cwd: ${cwd}`); } @@ -64,11 +63,11 @@ export default function resolveConfigPath( } const resolveConfigPathByTraversing = ( - pathToResolve: Config.Path, - initialPath: Config.Path, - cwd: Config.Path, + pathToResolve: string, + initialPath: string, + cwd: string, skipMultipleConfigWarning: boolean, -): Config.Path => { +): string => { const configFiles = JEST_CONFIG_EXT_ORDER.map(ext => path.resolve(pathToResolve, getConfigFilename(ext)), ).filter(isFile); @@ -101,7 +100,7 @@ const resolveConfigPathByTraversing = ( ); }; -const findPackageJson = (pathToResolve: Config.Path) => { +const findPackageJson = (pathToResolve: string) => { const packagePath = path.resolve(pathToResolve, PACKAGE_JSON); if (isFile(packagePath)) { return packagePath; @@ -110,7 +109,7 @@ const findPackageJson = (pathToResolve: Config.Path) => { return undefined; }; -const hasPackageJsonJestKey = (packagePath: Config.Path) => { +const hasPackageJsonJestKey = (packagePath: string) => { const content = fs.readFileSync(packagePath, 'utf8'); try { return 'jest' in JSON.parse(content); @@ -120,10 +119,7 @@ const hasPackageJsonJestKey = (packagePath: Config.Path) => { } }; -const makeResolutionErrorMessage = ( - initialPath: Config.Path, - cwd: Config.Path, -) => +const makeResolutionErrorMessage = (initialPath: string, cwd: string) => 'Could not find a config file based on provided values:\n' + `path: "${initialPath}"\n` + `cwd: "${cwd}"\n` + @@ -133,7 +129,7 @@ const makeResolutionErrorMessage = ( ext => `"${getConfigFilename(ext)}"`, ).join(' or ')}.`; -function extraIfPackageJson(configPath: Config.Path) { +function extraIfPackageJson(configPath: string) { if (configPath.endsWith(PACKAGE_JSON)) { return '`jest` key in '; } @@ -141,7 +137,7 @@ function extraIfPackageJson(configPath: Config.Path) { return ''; } -const makeMultipleConfigsWarning = (configPaths: Array) => +const makeMultipleConfigsWarning = (configPaths: Array) => chalk.yellow( [ chalk.bold('\u25cf Multiple configurations found:'), diff --git a/packages/jest-config/src/utils.ts b/packages/jest-config/src/utils.ts index 9958f6b6bcaf..324975d98626 100644 --- a/packages/jest-config/src/utils.ts +++ b/packages/jest-config/src/utils.ts @@ -7,14 +7,13 @@ import * as path from 'path'; import chalk = require('chalk'); -import type {Config} from '@jest/types'; import Resolver from 'jest-resolve'; import {ValidationError} from 'jest-validate'; type ResolveOptions = { - rootDir: Config.Path; + rootDir: string; key: string; - filePath: Config.Path; + filePath: string; optional?: boolean; }; @@ -52,12 +51,12 @@ export const resolve = ( return module as string; }; -export const escapeGlobCharacters = (path: Config.Path): Config.Glob => +export const escapeGlobCharacters = (path: string): string => path.replace(/([()*{}\[\]!?\\])/g, '\\$1'); export const replaceRootDirInPath = ( - rootDir: Config.Path, - filePath: Config.Path, + rootDir: string, + filePath: string, ): string => { if (!/^/.test(filePath)) { return filePath; @@ -70,7 +69,7 @@ export const replaceRootDirInPath = ( }; const _replaceRootDirInObject = ( - rootDir: Config.Path, + rootDir: string, config: T, ): T => { const newConfig = {} as T; @@ -84,14 +83,14 @@ const _replaceRootDirInObject = ( }; type OrArray = T | Array; -type ReplaceRootDirConfigObj = Record; +type ReplaceRootDirConfigObj = Record; type ReplaceRootDirConfigValues = | OrArray | OrArray - | OrArray; + | OrArray; export const _replaceRootDirTags = ( - rootDir: Config.Path, + rootDir: string, config: T, ): T => { if (config == null) { diff --git a/packages/jest-core/src/SearchSource.ts b/packages/jest-core/src/SearchSource.ts index ad03652d18f4..8340dacdec5a 100644 --- a/packages/jest-core/src/SearchSource.ts +++ b/packages/jest-core/src/SearchSource.ts @@ -31,7 +31,7 @@ export type TestSelectionConfig = { input?: string; findRelatedTests?: boolean; onlyChanged?: boolean; - paths?: Array; + paths?: Array; shouldTreatInputAsPattern?: boolean; testPathPattern?: string; watch?: boolean; @@ -40,7 +40,7 @@ export type TestSelectionConfig = { const regexToMatcher = (testRegex: Config.ProjectConfig['testRegex']) => { const regexes = testRegex.map(testRegex => new RegExp(testRegex)); - return (path: Config.Path) => + return (path: string) => regexes.some(regex => { const result = regex.test(path); @@ -51,7 +51,7 @@ const regexToMatcher = (testRegex: Config.ProjectConfig['testRegex']) => { }); }; -const toTests = (context: Context, tests: Array) => +const toTests = (context: Context, tests: Array) => tests.map(path => ({ context, duration: undefined, @@ -142,7 +142,7 @@ export default class SearchSource { if (testPathPattern) { const regex = testPathPatternToRegExp(testPathPattern); testCases.push({ - isMatch: (path: Config.Path) => regex.test(path), + isMatch: (path: string) => regex.test(path), stat: 'testPathPattern', }); data.stats.testPathPattern = 0; @@ -170,7 +170,7 @@ export default class SearchSource { ); } - isTestFilePath(path: Config.Path): boolean { + isTestFilePath(path: string): boolean { return this._testPathCases.every(testCase => testCase.isMatch(path)); } @@ -179,7 +179,7 @@ export default class SearchSource { } async findRelatedTests( - allPaths: Set, + allPaths: Set, collectCoverage: boolean, ): Promise { const dependencyResolver = await this._getOrBuildDependencyResolver(); @@ -235,7 +235,7 @@ export default class SearchSource { }; } - findTestsByPaths(paths: Array): SearchResult { + findTestsByPaths(paths: Array): SearchResult { return { tests: toTests( this._context, @@ -247,7 +247,7 @@ export default class SearchSource { } async findRelatedTestsFromPattern( - paths: Array, + paths: Array, collectCoverage: boolean, ): Promise { if (Array.isArray(paths) && paths.length) { diff --git a/packages/jest-core/src/TestScheduler.ts b/packages/jest-core/src/TestScheduler.ts index 0f0ca9e4218c..17fdff1935f4 100644 --- a/packages/jest-core/src/TestScheduler.ts +++ b/packages/jest-core/src/TestScheduler.ts @@ -46,8 +46,8 @@ export type TestSchedulerOptions = { export type TestSchedulerContext = { firstRun: boolean; previousSuccess: boolean; - changedFiles?: Set; - sourcesRelatedToTestsInChangedFiles?: Set; + changedFiles?: Set; + sourcesRelatedToTestsInChangedFiles?: Set; }; export async function createTestScheduler( diff --git a/packages/jest-core/src/__tests__/SearchSource.test.ts b/packages/jest-core/src/__tests__/SearchSource.test.ts index 76122f957363..3922665cbb8a 100644 --- a/packages/jest-core/src/__tests__/SearchSource.test.ts +++ b/packages/jest-core/src/__tests__/SearchSource.test.ts @@ -579,7 +579,7 @@ describe('SearchSource', () => { }); it('returns empty search result for empty input', async () => { - const input: Array = []; + const input: Array = []; const data = await searchSource.findRelatedTestsFromPattern(input, false); expect(data.tests).toEqual([]); }); diff --git a/packages/jest-core/src/cli/index.ts b/packages/jest-core/src/cli/index.ts index 8a546027d6b5..b6e6e5d77681 100644 --- a/packages/jest-core/src/cli/index.ts +++ b/packages/jest-core/src/cli/index.ts @@ -36,7 +36,7 @@ type OnCompleteCallback = (results: AggregatedResult) => void | undefined; export async function runCLI( argv: Config.Argv, - projects: Array, + projects: Array, ): Promise<{ results: AggregatedResult; globalConfig: Config.GlobalConfig; diff --git a/packages/jest-core/src/getChangedFilesPromise.ts b/packages/jest-core/src/getChangedFilesPromise.ts index b628bfee04b7..c31031dd84b6 100644 --- a/packages/jest-core/src/getChangedFilesPromise.ts +++ b/packages/jest-core/src/getChangedFilesPromise.ts @@ -15,7 +15,7 @@ export default function getChangedFilesPromise( configs: Array, ): ChangedFilesPromise | undefined { if (globalConfig.onlyChanged) { - const allRootsForAllProjects = configs.reduce>( + const allRootsForAllProjects = configs.reduce>( (roots, config) => { if (config.roots) { roots.push(...config.roots); diff --git a/packages/jest-core/src/lib/isValidPath.ts b/packages/jest-core/src/lib/isValidPath.ts index 65180f844623..d088c9904ea1 100644 --- a/packages/jest-core/src/lib/isValidPath.ts +++ b/packages/jest-core/src/lib/isValidPath.ts @@ -10,7 +10,7 @@ import {isSnapshotPath} from 'jest-snapshot'; export default function isValidPath( globalConfig: Config.GlobalConfig, - filePath: Config.Path, + filePath: string, ): boolean { return ( !filePath.includes(globalConfig.coverageDirectory) && diff --git a/packages/jest-core/src/types.ts b/packages/jest-core/src/types.ts index b51174cafad9..f29b8b3e2535 100644 --- a/packages/jest-core/src/types.ts +++ b/packages/jest-core/src/types.ts @@ -6,7 +6,6 @@ */ import type {Test} from '@jest/test-result'; -import type {Config} from '@jest/types'; import type {Context} from 'jest-runtime'; export type Stats = { @@ -29,11 +28,11 @@ export type TestRunData = Array<{ export type TestPathCases = Array<{ stat: keyof Stats; - isMatch: (path: Config.Path) => boolean; + isMatch: (path: string) => boolean; }>; export type TestPathCasesWithPathPattern = TestPathCases & { - testPathPattern: (path: Config.Path) => boolean; + testPathPattern: (path: string) => boolean; }; export type FilterResult = { diff --git a/packages/jest-create-cache-key-function/src/index.ts b/packages/jest-create-cache-key-function/src/index.ts index fe042dfccb89..8f1a6f1eed80 100644 --- a/packages/jest-create-cache-key-function/src/index.ts +++ b/packages/jest-create-cache-key-function/src/index.ts @@ -26,7 +26,7 @@ type NewCacheKeyOptions = { type OldGetCacheKeyFunction = ( fileData: string, - filePath: Config.Path, + filePath: string, configStr: string, options: OldCacheKeyOptions, ) => string; @@ -34,7 +34,7 @@ type OldGetCacheKeyFunction = ( // Should mirror `import('@jest/transform').Transformer['getCacheKey']` type NewGetCacheKeyFunction = ( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, options: NewCacheKeyOptions, ) => string; diff --git a/packages/jest-environment/src/index.ts b/packages/jest-environment/src/index.ts index 509a4dac4fad..5f589c7e9b93 100644 --- a/packages/jest-environment/src/index.ts +++ b/packages/jest-environment/src/index.ts @@ -18,7 +18,7 @@ import type { export type EnvironmentContext = { console: Console; docblockPragmas: Record>; - testPath: Config.Path; + testPath: string; }; // Different Order than https://nodejs.org/api/modules.html#modules_the_module_wrapper , however needs to be in the form [jest-transform]ScriptTransformer accepts diff --git a/packages/jest-haste-map/src/HasteFS.ts b/packages/jest-haste-map/src/HasteFS.ts index 64478ee22871..56fd2792067c 100644 --- a/packages/jest-haste-map/src/HasteFS.ts +++ b/packages/jest-haste-map/src/HasteFS.ts @@ -5,32 +5,31 @@ * LICENSE file in the root directory of this source tree. */ -import type {Config} from '@jest/types'; import {globsToMatcher, replacePathSepForGlob} from 'jest-util'; import H from './constants'; import * as fastPath from './lib/fast_path'; import type {FileData} from './types'; export default class HasteFS { - private readonly _rootDir: Config.Path; + private readonly _rootDir: string; private readonly _files: FileData; - constructor({rootDir, files}: {rootDir: Config.Path; files: FileData}) { + constructor({rootDir, files}: {rootDir: string; files: FileData}) { this._rootDir = rootDir; this._files = files; } - getModuleName(file: Config.Path): string | null { + getModuleName(file: string): string | null { const fileMetadata = this._getFileData(file); return (fileMetadata && fileMetadata[H.ID]) || null; } - getSize(file: Config.Path): number | null { + getSize(file: string): number | null { const fileMetadata = this._getFileData(file); return (fileMetadata && fileMetadata[H.SIZE]) || null; } - getDependencies(file: Config.Path): Array | null { + getDependencies(file: string): Array | null { const fileMetadata = this._getFileData(file); if (fileMetadata) { @@ -42,30 +41,30 @@ export default class HasteFS { } } - getSha1(file: Config.Path): string | null { + getSha1(file: string): string | null { const fileMetadata = this._getFileData(file); return (fileMetadata && fileMetadata[H.SHA1]) || null; } - exists(file: Config.Path): boolean { + exists(file: string): boolean { return this._getFileData(file) != null; } - getAllFiles(): Array { + getAllFiles(): Array { return Array.from(this.getAbsoluteFileIterator()); } - getFileIterator(): Iterable { + getFileIterator(): Iterable { return this._files.keys(); } - *getAbsoluteFileIterator(): Iterable { + *getAbsoluteFileIterator(): Iterable { for (const file of this.getFileIterator()) { yield fastPath.resolve(this._rootDir, file); } } - matchFiles(pattern: RegExp | string): Array { + matchFiles(pattern: RegExp | string): Array { if (!(pattern instanceof RegExp)) { pattern = new RegExp(pattern); } @@ -78,10 +77,7 @@ export default class HasteFS { return files; } - matchFilesWithGlob( - globs: Array, - root: Config.Path | null, - ): Set { + matchFilesWithGlob(globs: Array, root: string | null): Set { const files = new Set(); const matcher = globsToMatcher(globs); @@ -94,7 +90,7 @@ export default class HasteFS { return files; } - private _getFileData(file: Config.Path) { + private _getFileData(file: string) { const relativePath = fastPath.relative(this._rootDir, file); return this._files.get(relativePath); } diff --git a/packages/jest-haste-map/src/ModuleMap.ts b/packages/jest-haste-map/src/ModuleMap.ts index 960af85e33b3..c2b98bd33a5e 100644 --- a/packages/jest-haste-map/src/ModuleMap.ts +++ b/packages/jest-haste-map/src/ModuleMap.ts @@ -5,7 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -import type {Config} from '@jest/types'; import H from './constants'; import * as fastPath from './lib/fast_path'; import type { @@ -58,7 +57,7 @@ export default class ModuleMap implements IModuleMap { platform?: string | null, supportsNativePlatform?: boolean | null, type?: HTypeValue | null, - ): Config.Path | null { + ): string | null { if (type == null) { type = H.MODULE; } @@ -78,11 +77,11 @@ export default class ModuleMap implements IModuleMap { name: string, platform: string | null | undefined, _supportsNativePlatform: boolean | null, - ): Config.Path | null { + ): string | null { return this.getModule(name, platform, null, H.PACKAGE); } - getMockModule(name: string): Config.Path | undefined { + getMockModule(name: string): string | undefined { const mockPath = this._raw.mocks.get(name) || this._raw.mocks.get(name + '/index'); return mockPath && fastPath.resolve(this._raw.rootDir, mockPath); @@ -197,7 +196,7 @@ export default class ModuleMap implements IModuleMap { ); } - static create(rootDir: Config.Path): ModuleMap { + static create(rootDir: string): ModuleMap { return new ModuleMap({ duplicates: new Map(), map: new Map(), diff --git a/packages/jest-haste-map/src/crawlers/watchman.ts b/packages/jest-haste-map/src/crawlers/watchman.ts index fff05af78795..1fbe14c3460b 100644 --- a/packages/jest-haste-map/src/crawlers/watchman.ts +++ b/packages/jest-haste-map/src/crawlers/watchman.ts @@ -7,7 +7,6 @@ import * as path from 'path'; import watchman = require('fb-watchman'); -import type {Config} from '@jest/types'; import H from '../constants'; import * as fastPath from '../lib/fast_path'; import normalizePathSep from '../lib/normalizePathSep'; @@ -142,7 +141,7 @@ export async function watchmanCrawl(options: CrawlerOptions): Promise<{ } async function getWatchmanRoots( - roots: Array, + roots: Array, ): Promise { const watchmanRoots = new Map(); await Promise.all( diff --git a/packages/jest-haste-map/src/index.ts b/packages/jest-haste-map/src/index.ts index cfe65b017109..b87b9c13111a 100644 --- a/packages/jest-haste-map/src/index.ts +++ b/packages/jest-haste-map/src/index.ts @@ -216,7 +216,7 @@ function invariant(condition: unknown, message?: string): asserts condition { */ export default class HasteMap extends EventEmitter { private _buildPromise: Promise | null; - private _cachePath: Config.Path; + private _cachePath: string; private _changeInterval?: ReturnType; private _console: Console; private _options: InternalOptions; @@ -333,7 +333,7 @@ export default class HasteMap extends EventEmitter { } static getCacheFilePath( - tmpdir: Config.Path, + tmpdir: string, name: string, ...extra: Array ): string { @@ -445,7 +445,7 @@ export default class HasteMap extends EventEmitter { hasteMap: InternalHasteMap, map: ModuleMapData, mocks: MockData, - filePath: Config.Path, + filePath: string, workerOptions?: {forceInBand: boolean}, ): Promise | null { const rootDir = this._options.rootDir; @@ -828,7 +828,7 @@ export default class HasteMap extends EventEmitter { // We only need to copy the entire haste map once on every "frame". let mustCopy = true; - const createWatcher = (root: Config.Path): Promise => { + const createWatcher = (root: string): Promise => { const watcher = new Watcher(root, { dot: true, glob: extensions.map(extension => '**/*.' + extension), @@ -869,8 +869,8 @@ export default class HasteMap extends EventEmitter { const onChange = ( type: string, - filePath: Config.Path, - root: Config.Path, + filePath: string, + root: string, stat?: Stats, ) => { filePath = path.join(root, normalizePathSep(filePath)); @@ -1087,7 +1087,7 @@ export default class HasteMap extends EventEmitter { /** * Helpers */ - private _ignore(filePath: Config.Path): boolean { + private _ignore(filePath: string): boolean { const ignorePattern = this._options.ignorePattern; const ignoreMatched = ignorePattern instanceof RegExp diff --git a/packages/jest-haste-map/src/types.ts b/packages/jest-haste-map/src/types.ts index 501afaedddc3..28515e6090ac 100644 --- a/packages/jest-haste-map/src/types.ts +++ b/packages/jest-haste-map/src/types.ts @@ -6,7 +6,6 @@ */ import type {Stats} from 'graceful-fs'; -import type {Config} from '@jest/types'; import type HasteFS from './HasteFS'; import type ModuleMap from './ModuleMap'; @@ -16,7 +15,7 @@ export type SerializableModuleMap = { duplicates: ReadonlyArray<[string, [string, [string, [string, number]]]]>; map: ReadonlyArray<[string, ValueType]>; mocks: ReadonlyArray<[string, ValueType]>; - rootDir: Config.Path; + rootDir: string; }; export interface IModuleMap { @@ -25,15 +24,15 @@ export interface IModuleMap { platform?: string | null, supportsNativePlatform?: boolean | null, type?: HTypeValue | null, - ): Config.Path | null; + ): string | null; getPackage( name: string, platform: string | null | undefined, _supportsNativePlatform: boolean | null, - ): Config.Path | null; + ): string | null; - getMockModule(name: string): Config.Path | undefined; + getMockModule(name: string): string | undefined; getRawModuleMap(): RawModuleMap; @@ -42,7 +41,7 @@ export interface IModuleMap { export type HasteMapStatic = { getCacheFilePath( - tmpdir: Config.Path, + tmpdir: string, name: string, ...extra: Array ): string; @@ -79,10 +78,10 @@ export type CrawlerOptions = { }; export type HasteImpl = { - getHasteName(filePath: Config.Path): string | undefined; + getHasteName(filePath: string): string | undefined; }; -export type FileData = Map; +export type FileData = Map; export type FileMetaData = [ id: string, @@ -93,10 +92,10 @@ export type FileMetaData = [ sha1: string | null | undefined, ]; -export type MockData = Map; +export type MockData = Map; export type ModuleMapData = Map; export type WatchmanClockSpec = string | {scm: {'mergebase-with': string}}; -export type WatchmanClocks = Map; +export type WatchmanClocks = Map; export type HasteRegExp = RegExp | ((str: string) => boolean); export type DuplicatesSet = Map; @@ -116,14 +115,14 @@ export type HasteMap = { }; export type RawModuleMap = { - rootDir: Config.Path; + rootDir: string; duplicates: DuplicatesIndex; map: ModuleMapData; mocks: MockData; }; type ModuleMapItem = {[platform: string]: ModuleMetaData}; -export type ModuleMetaData = [path: Config.Path, type: number]; +export type ModuleMetaData = [path: string, type: number]; export type HType = { ID: 0; @@ -144,7 +143,7 @@ export type HType = { export type HTypeValue = HType[keyof HType]; export type EventsQueue = Array<{ - filePath: Config.Path; + filePath: string; stat: Stats | undefined; type: string; }>; diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index 884cadf399b1..d8f1a14bc4f5 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -17,6 +17,7 @@ import {installErrorOnPrivate} from './errorOnPrivate'; import type Spec from './jasmine/Spec'; import jasmineAsyncInstall from './jasmineAsyncInstall'; import JasmineReporter from './reporter'; + export type {Jasmine} from './types'; const JASMINE = require.resolve('./jasmine/jasmineLight'); diff --git a/packages/jest-jasmine2/src/jasmine/Spec.ts b/packages/jest-jasmine2/src/jasmine/Spec.ts index 4043416075e2..0767a720e940 100644 --- a/packages/jest-jasmine2/src/jasmine/Spec.ts +++ b/packages/jest-jasmine2/src/jasmine/Spec.ts @@ -32,7 +32,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import {AssertionError} from 'assert'; import type {FailedAssertion, Milliseconds, Status} from '@jest/test-result'; -import type {Config} from '@jest/types'; import ExpectationFailed from '../ExpectationFailed'; import assertionErrorMessage from '../assertionErrorMessage'; import expectationResultFactory, { @@ -46,7 +45,7 @@ export type Attributes = { resultCallback: (result: Spec['result']) => void; description: string; throwOnExpectationFailure: unknown; - getTestPath: () => Config.Path; + getTestPath: () => string; queueableFn: QueueableFn; beforeAndAfterFns: () => { befores: Array; @@ -64,7 +63,7 @@ export type SpecResult = { fullName: string; duration?: Milliseconds; failedExpectations: Array; - testPath: Config.Path; + testPath: string; passedExpectations: Array>; pendingReason: string; status: Status; diff --git a/packages/jest-jasmine2/src/jasmine/Suite.ts b/packages/jest-jasmine2/src/jasmine/Suite.ts index 271392dfd1b7..b815ae31d41d 100644 --- a/packages/jest-jasmine2/src/jasmine/Suite.ts +++ b/packages/jest-jasmine2/src/jasmine/Suite.ts @@ -31,7 +31,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /* eslint-disable sort-keys, local/prefer-spread-eventually, local/prefer-rest-params-eventually */ -import type {Config} from '@jest/types'; import {convertDescriptorToString} from 'jest-util'; import ExpectationFailed from '../ExpectationFailed'; import expectationResultFactory from '../expectationResultFactory'; @@ -43,7 +42,7 @@ export type SuiteResult = { description: string; fullName: string; failedExpectations: Array>; - testPath: Config.Path; + testPath: string; status?: string; }; @@ -52,7 +51,7 @@ export type Attributes = { parentSuite?: Suite; description: string; throwOnExpectationFailure?: boolean; - getTestPath: () => Config.Path; + getTestPath: () => string; }; export default class Suite { diff --git a/packages/jest-jasmine2/src/reporter.ts b/packages/jest-jasmine2/src/reporter.ts index 507295b0f946..3f1353dfa0dd 100644 --- a/packages/jest-jasmine2/src/reporter.ts +++ b/packages/jest-jasmine2/src/reporter.ts @@ -26,12 +26,12 @@ export default class Jasmine2Reporter implements Reporter { private _resolve: any; private _resultsPromise: Promise; private _startTimes: Map; - private _testPath: Config.Path; + private _testPath: string; constructor( globalConfig: Config.GlobalConfig, config: Config.ProjectConfig, - testPath: Config.Path, + testPath: string, ) { this._globalConfig = globalConfig; this._config = config; diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index ceddb98beba6..d16c34685009 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -23,7 +23,7 @@ export type SetupOptions = { config: Config.ProjectConfig; globalConfig: Config.GlobalConfig; localRequire: (moduleName: string) => Plugin; - testPath: Config.Path; + testPath: string; }; // Get suppressed errors form jest-matchers that weren't throw during diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts index c444f8e77a98..4f42b280fb96 100644 --- a/packages/jest-jasmine2/src/types.ts +++ b/packages/jest-jasmine2/src/types.ts @@ -6,7 +6,6 @@ */ import type {AssertionError} from 'assert'; -import type {Config} from '@jest/types'; import type {Expect} from 'expect'; import type CallTracker from './jasmine/CallTracker'; import type Env from './jasmine/Env'; @@ -68,7 +67,7 @@ export type Jasmine = { Suite: typeof Suite; Timer: typeof Timer; version: string; - testPath: Config.Path; + testPath: string; addMatchers: (matchers: JasmineMatchersObject) => void; } & Expect & typeof globalThis; diff --git a/packages/jest-message-util/src/index.ts b/packages/jest-message-util/src/index.ts index 1aa0899e5bbf..c06442303994 100644 --- a/packages/jest-message-util/src/index.ts +++ b/packages/jest-message-util/src/index.ts @@ -19,8 +19,6 @@ import type {Frame} from './types'; export type {Frame} from './types'; -type Path = Config.Path; - // stack utils tries to create pretty stack by making paths relative. const stackUtils = new StackUtils({cwd: 'something which does not exist'}); @@ -127,7 +125,7 @@ export const formatExecError = ( error: Error | TestResult.SerializableError | string | undefined, config: StackTraceConfig, options: StackTraceOptions, - testPath?: Path, + testPath?: string, reuseMessage?: boolean, ): string => { if (!error || typeof error === 'number') { @@ -238,7 +236,7 @@ const removeInternalStackEntries = ( const formatPaths = ( config: StackTraceConfig, - relativeTestPath: Path | null, + relativeTestPath: string | null, line: string, ) => { // Extract the file path from the trace line. @@ -288,7 +286,7 @@ export const formatStackTrace = ( stack: string, config: StackTraceConfig, options: StackTraceOptions, - testPath?: Path, + testPath?: string, ): string => { const lines = getStackTraceLines(stack, options); let renderedCallsite = ''; @@ -337,7 +335,7 @@ export const formatResultsErrors = ( testResults: Array, config: StackTraceConfig, options: StackTraceOptions, - testPath?: Path, + testPath?: string, ): string | null => { const failedResults: FailedResults = testResults.reduce( (errors, result) => { diff --git a/packages/jest-reporters/src/CoverageWorker.ts b/packages/jest-reporters/src/CoverageWorker.ts index 11396ac9cbe2..b7f9741c0320 100644 --- a/packages/jest-reporters/src/CoverageWorker.ts +++ b/packages/jest-reporters/src/CoverageWorker.ts @@ -16,7 +16,7 @@ import type {CoverageReporterSerializedOptions} from './types'; export type CoverageWorkerData = { globalConfig: Config.GlobalConfig; config: Config.ProjectConfig; - path: Config.Path; + path: string; options?: CoverageReporterSerializedOptions; }; diff --git a/packages/jest-reporters/src/DefaultReporter.ts b/packages/jest-reporters/src/DefaultReporter.ts index d9aeee5b210a..9000370519cb 100644 --- a/packages/jest-reporters/src/DefaultReporter.ts +++ b/packages/jest-reporters/src/DefaultReporter.ts @@ -180,7 +180,7 @@ export default class DefaultReporter extends BaseReporter { } printTestFileHeader( - _testPath: Config.Path, + _testPath: string, config: Config.ProjectConfig, result: TestResult, ): void { @@ -196,7 +196,7 @@ export default class DefaultReporter extends BaseReporter { } printTestFileFailureMessage( - _testPath: Config.Path, + _testPath: string, _config: Config.ProjectConfig, result: TestResult, ): void { diff --git a/packages/jest-reporters/src/Status.ts b/packages/jest-reporters/src/Status.ts index 839bb870ba27..697c12cc2de3 100644 --- a/packages/jest-reporters/src/Status.ts +++ b/packages/jest-reporters/src/Status.ts @@ -31,7 +31,7 @@ const RUNNING = chalk.reset.inverse.yellow.bold(RUNNING_TEXT) + ' '; */ class CurrentTestList { private _array: Array<{ - testPath: Config.Path; + testPath: string; config: Config.ProjectConfig; } | null>; @@ -39,7 +39,7 @@ class CurrentTestList { this._array = []; } - add(testPath: Config.Path, config: Config.ProjectConfig) { + add(testPath: string, config: Config.ProjectConfig) { const index = this._array.indexOf(null); const record = {config, testPath}; if (index !== -1) { @@ -49,7 +49,7 @@ class CurrentTestList { } } - delete(testPath: Config.Path) { + delete(testPath: string) { const record = this._array.find( record => record !== null && record.testPath === testPath, ); @@ -126,7 +126,7 @@ export default class Status { } } - testStarted(testPath: Config.Path, config: Config.ProjectConfig): void { + testStarted(testPath: string, config: Config.ProjectConfig): void { this._currentTests.add(testPath, config); if (!this._showStatus) { this._emit(); diff --git a/packages/jest-reporters/src/generateEmptyCoverage.ts b/packages/jest-reporters/src/generateEmptyCoverage.ts index af9effddbc93..72e35e4b73f8 100644 --- a/packages/jest-reporters/src/generateEmptyCoverage.ts +++ b/packages/jest-reporters/src/generateEmptyCoverage.ts @@ -26,11 +26,11 @@ export type CoverageWorkerResult = export default async function generateEmptyCoverage( source: string, - filename: Config.Path, + filename: string, globalConfig: Config.GlobalConfig, config: Config.ProjectConfig, - changedFiles?: Set, - sourcesRelatedToTestsInChangedFiles?: Set, + changedFiles?: Set, + sourcesRelatedToTestsInChangedFiles?: Set, ): Promise { const coverageOptions = { changedFiles, diff --git a/packages/jest-reporters/src/types.ts b/packages/jest-reporters/src/types.ts index d4040ed1f201..693454d007af 100644 --- a/packages/jest-reporters/src/types.ts +++ b/packages/jest-reporters/src/types.ts @@ -31,19 +31,19 @@ export type Context = { export type Test = { context: Context; duration?: number; - path: Config.Path; + path: string; }; export type CoverageWorker = {worker: typeof worker}; export type CoverageReporterOptions = { - changedFiles?: Set; - sourcesRelatedToTestsInChangedFiles?: Set; + changedFiles?: Set; + sourcesRelatedToTestsInChangedFiles?: Set; }; export type CoverageReporterSerializedOptions = { - changedFiles?: Array; - sourcesRelatedToTestsInChangedFiles?: Array; + changedFiles?: Array; + sourcesRelatedToTestsInChangedFiles?: Array; }; export type OnTestStart = (test: Test) => Promise; @@ -103,5 +103,5 @@ export type TestRunData = Array<{ export type TestSchedulerContext = { firstRun: boolean; previousSuccess: boolean; - changedFiles?: Set; + changedFiles?: Set; }; diff --git a/packages/jest-reporters/src/utils.ts b/packages/jest-reporters/src/utils.ts index 4826c3a7017e..0c3ec13c9eb1 100644 --- a/packages/jest-reporters/src/utils.ts +++ b/packages/jest-reporters/src/utils.ts @@ -32,7 +32,7 @@ export const printDisplayName = (config: Config.ProjectConfig): string => { export const trimAndFormatPath = ( pad: number, config: Config.ProjectConfig | Config.GlobalConfig, - testPath: Config.Path, + testPath: string, columns: number, ): string => { const maxLength = columns - pad; @@ -68,7 +68,7 @@ export const trimAndFormatPath = ( export const formatTestPath = ( config: Config.GlobalConfig | Config.ProjectConfig, - testPath: Config.Path, + testPath: string, ): string => { const {dirname, basename} = relativePath(config, testPath); return slash(chalk.dim(dirname + path.sep) + chalk.bold(basename)); @@ -76,7 +76,7 @@ export const formatTestPath = ( export const relativePath = ( config: Config.GlobalConfig | Config.ProjectConfig, - testPath: Config.Path, + testPath: string, ): {basename: string; dirname: string} => { // this function can be called with ProjectConfigs or GlobalConfigs. GlobalConfigs // do not have config.cwd, only config.rootDir. Try using config.cwd, fallback diff --git a/packages/jest-resolve-dependencies/package.json b/packages/jest-resolve-dependencies/package.json index 09dc7e679286..07ec97955f34 100644 --- a/packages/jest-resolve-dependencies/package.json +++ b/packages/jest-resolve-dependencies/package.json @@ -17,12 +17,12 @@ "./package.json": "./package.json" }, "dependencies": { - "@jest/types": "^28.0.0-alpha.1", "jest-regex-util": "^28.0.0-alpha.0", "jest-snapshot": "^28.0.0-alpha.1" }, "devDependencies": { "@jest/test-utils": "^28.0.0-alpha.1", + "@jest/types": "^28.0.0-alpha.1", "jest-haste-map": "^28.0.0-alpha.1", "jest-resolve": "^28.0.0-alpha.1", "jest-runtime": "^28.0.0-alpha.1" diff --git a/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.ts b/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.ts index a06636e4d4e4..35b28ed79f07 100644 --- a/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.ts +++ b/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.ts @@ -22,7 +22,7 @@ const cases: Record = { fancyCondition: jest.fn(path => path.length > 10), testRegex: jest.fn(path => /.test.js$/.test(path)), }; -const filter = (path: Config.Path) => +const filter = (path: string) => Object.keys(cases).every(key => cases[key](path)); beforeEach(async () => { diff --git a/packages/jest-resolve-dependencies/src/index.ts b/packages/jest-resolve-dependencies/src/index.ts index 32fce32dbe54..21ba04ac3115 100644 --- a/packages/jest-resolve-dependencies/src/index.ts +++ b/packages/jest-resolve-dependencies/src/index.ts @@ -6,14 +6,13 @@ */ import * as path from 'path'; -import type {Config} from '@jest/types'; import type {FS as HasteFS} from 'jest-haste-map'; import type {ResolveModuleConfig, default as Resolver} from 'jest-resolve'; import {SnapshotResolver, isSnapshotPath} from 'jest-snapshot'; export type ResolvedModule = { - file: Config.Path; - dependencies: Array; + file: string; + dependencies: Array; }; /** @@ -35,16 +34,13 @@ export class DependencyResolver { this._snapshotResolver = snapshotResolver; } - resolve( - file: Config.Path, - options?: ResolveModuleConfig, - ): Array { + resolve(file: string, options?: ResolveModuleConfig): Array { const dependencies = this._hasteFS.getDependencies(file); if (!dependencies) { return []; } - return dependencies.reduce>((acc, dependency) => { + return dependencies.reduce>((acc, dependency) => { if (this._resolver.isCoreModule(dependency)) { return acc; } @@ -101,8 +97,8 @@ export class DependencyResolver { } resolveInverseModuleMap( - paths: Set, - filter: (file: Config.Path) => boolean, + paths: Set, + filter: (file: string) => boolean, options?: ResolveModuleConfig, ): Array { if (!paths.size) { @@ -110,15 +106,15 @@ export class DependencyResolver { } const collectModules = ( - related: Set, + related: Set, moduleMap: Array, - changed: Set, + changed: Set, ) => { const visitedModules = new Set(); const result: Array = []; while (changed.size) { changed = new Set( - moduleMap.reduce>((acc, module) => { + moduleMap.reduce>((acc, module) => { if ( visitedModules.has(module.file) || !module.dependencies.some(dep => changed.has(dep)) @@ -142,8 +138,8 @@ export class DependencyResolver { ); }; - const relatedPaths = new Set(); - const changed: Set = new Set(); + const relatedPaths = new Set(); + const changed: Set = new Set(); for (const path of paths) { if (this._hasteFS.exists(path)) { const modulePath = isSnapshotPath(path) @@ -166,10 +162,10 @@ export class DependencyResolver { } resolveInverse( - paths: Set, - filter: (file: Config.Path) => boolean, + paths: Set, + filter: (file: string) => boolean, options?: ResolveModuleConfig, - ): Array { + ): Array { return this.resolveInverseModuleMap(paths, filter, options).map( module => module.file, ); diff --git a/packages/jest-resolve/package.json b/packages/jest-resolve/package.json index b4273110ad10..44a5e8d9b393 100644 --- a/packages/jest-resolve/package.json +++ b/packages/jest-resolve/package.json @@ -17,7 +17,6 @@ "./package.json": "./package.json" }, "dependencies": { - "@jest/types": "^28.0.0-alpha.1", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^28.0.0-alpha.1", diff --git a/packages/jest-resolve/src/ModuleNotFoundError.ts b/packages/jest-resolve/src/ModuleNotFoundError.ts index a2b0935c6348..7b6685c5ba96 100644 --- a/packages/jest-resolve/src/ModuleNotFoundError.ts +++ b/packages/jest-resolve/src/ModuleNotFoundError.ts @@ -7,12 +7,11 @@ import * as path from 'path'; import slash = require('slash'); -import type {Config} from '@jest/types'; export default class ModuleNotFoundError extends Error { public code = 'MODULE_NOT_FOUND'; public hint?: string; - public requireStack?: Array; + public requireStack?: Array; public siblingWithSimilarExtensionFound?: boolean; public moduleName?: string; @@ -24,7 +23,7 @@ export default class ModuleNotFoundError extends Error { this.moduleName = moduleName; } - public buildMessage(rootDir: Config.Path): void { + public buildMessage(rootDir: string): void { if (!this._originalMessage) { this._originalMessage = this.message || ''; } diff --git a/packages/jest-resolve/src/defaultResolver.ts b/packages/jest-resolve/src/defaultResolver.ts index 758117214744..1ca6204d0b6d 100644 --- a/packages/jest-resolve/src/defaultResolver.ts +++ b/packages/jest-resolve/src/defaultResolver.ts @@ -13,7 +13,6 @@ import { resolve as resolveExports, } from 'resolve.exports'; import slash = require('slash'); -import type {Config} from '@jest/types'; import { PkgJson, isDirectory, @@ -25,14 +24,14 @@ import { // copy from `resolve`'s types so we don't have their types in our definition // files interface ResolverOptions { - basedir: Config.Path; + basedir: string; browser?: boolean; conditions?: Array; defaultResolver: typeof defaultResolver; extensions?: Array; moduleDirectory?: Array; - paths?: Array; - rootDir?: Config.Path; + paths?: Array; + rootDir?: string; packageFilter?: (pkg: PkgJson, dir: string) => PkgJson; pathFilter?: (pkg: PkgJson, path: string, relativePath: string) => string; } @@ -47,9 +46,9 @@ declare global { } export default function defaultResolver( - path: Config.Path, + path: string, options: ResolverOptions, -): Config.Path { +): string { // Yarn 2 adds support to `resolve` automatically so the pnpResolver is only // needed for Yarn 1 which implements version 1 of the pnp spec if (process.versions.pnp === '1') { @@ -76,12 +75,12 @@ export default function defaultResolver( * helper functions */ -function readPackageSync(_: unknown, file: Config.Path): PkgJson { +function readPackageSync(_: unknown, file: string): PkgJson { return readPackageCached(file); } function createPackageFilter( - originalPath: Config.Path, + originalPath: string, userFilter?: ResolverOptions['packageFilter'], ): ResolverOptions['packageFilter'] { if (shouldIgnoreRequestForExports(originalPath)) { @@ -109,7 +108,7 @@ function createPackageFilter( } function createPathFilter( - originalPath: Config.Path, + originalPath: string, conditions?: Array, userFilter?: ResolverOptions['pathFilter'], ): ResolverOptions['pathFilter'] { @@ -144,5 +143,5 @@ function createPathFilter( } // if it's a relative import or an absolute path, exports are ignored -const shouldIgnoreRequestForExports = (path: Config.Path) => +const shouldIgnoreRequestForExports = (path: string) => path.startsWith('.') || isAbsolute(path); diff --git a/packages/jest-resolve/src/fileWalkers.ts b/packages/jest-resolve/src/fileWalkers.ts index 2b7fc52555d4..88c2110e9f72 100644 --- a/packages/jest-resolve/src/fileWalkers.ts +++ b/packages/jest-resolve/src/fileWalkers.ts @@ -7,7 +7,6 @@ import {dirname, resolve} from 'path'; import * as fs from 'graceful-fs'; -import type {Config} from '@jest/types'; import {tryRealpath} from 'jest-util'; export function clearFsCache(): void { @@ -53,7 +52,7 @@ function statSyncCached(path: string): IPathType { } const checkedRealpathPaths = new Map(); -function realpathCached(path: Config.Path): Config.Path { +function realpathCached(path: string): string { let result = checkedRealpathPaths.get(path); if (result != null) { @@ -75,7 +74,7 @@ function realpathCached(path: Config.Path): Config.Path { export type PkgJson = Record; const packageContents = new Map(); -export function readPackageCached(path: Config.Path): PkgJson { +export function readPackageCached(path: string): PkgJson { let result = packageContents.get(path); if (result != null) { @@ -92,9 +91,7 @@ export function readPackageCached(path: Config.Path): PkgJson { // adapted from // https://github.com/lukeed/escalade/blob/2477005062cdbd8407afc90d3f48f4930354252b/src/sync.js // to use cached `fs` calls -export function findClosestPackageJson( - start: Config.Path, -): Config.Path | undefined { +export function findClosestPackageJson(start: string): string | undefined { let dir = resolve('.', start); if (!isDirectory(dir)) { dir = dirname(dir); @@ -120,14 +117,14 @@ export function findClosestPackageJson( /* * helper functions */ -export function isFile(file: Config.Path): boolean { +export function isFile(file: string): boolean { return statSyncCached(file) === IPathType.FILE; } -export function isDirectory(dir: Config.Path): boolean { +export function isDirectory(dir: string): boolean { return statSyncCached(dir) === IPathType.DIRECTORY; } -export function realpathSync(file: Config.Path): Config.Path { +export function realpathSync(file: string): string { return realpathCached(file); } diff --git a/packages/jest-resolve/src/nodeModulesPaths.ts b/packages/jest-resolve/src/nodeModulesPaths.ts index 604e071c01fe..a2e91914de66 100644 --- a/packages/jest-resolve/src/nodeModulesPaths.ts +++ b/packages/jest-resolve/src/nodeModulesPaths.ts @@ -8,18 +8,17 @@ */ import * as path from 'path'; -import type {Config} from '@jest/types'; import {tryRealpath} from 'jest-util'; type NodeModulesPathsOptions = { moduleDirectory?: Array; - paths?: Array; + paths?: Array; }; export default function nodeModulesPaths( - basedir: Config.Path, + basedir: string, options: NodeModulesPathsOptions, -): Array { +): Array { const modules = options && options.moduleDirectory ? Array.from(options.moduleDirectory) @@ -46,7 +45,7 @@ export default function nodeModulesPaths( physicalBasedir = basedirAbs; } - const paths: Array = [physicalBasedir]; + const paths: Array = [physicalBasedir]; let parsed = path.parse(physicalBasedir); while (parsed.dir !== paths[paths.length - 1]) { paths.push(parsed.dir); @@ -54,7 +53,7 @@ export default function nodeModulesPaths( } const dirs = paths - .reduce>( + .reduce>( (dirs, aPath) => dirs.concat( modules.map(moduleDir => diff --git a/packages/jest-resolve/src/resolver.ts b/packages/jest-resolve/src/resolver.ts index 75c4018e4088..8eddb1bbd75d 100644 --- a/packages/jest-resolve/src/resolver.ts +++ b/packages/jest-resolve/src/resolver.ts @@ -10,7 +10,6 @@ import * as path from 'path'; import chalk = require('chalk'); import slash = require('slash'); -import type {Config} from '@jest/types'; import type {IModuleMap} from 'jest-haste-map'; import {tryRealpath} from 'jest-util'; import ModuleNotFoundError from './ModuleNotFoundError'; @@ -22,21 +21,21 @@ import shouldLoadAsEsm, {clearCachedLookups} from './shouldLoadAsEsm'; import type {ResolverConfig} from './types'; type FindNodeModuleConfig = { - basedir: Config.Path; + basedir: string; browser?: boolean; conditions?: Array; extensions?: Array; moduleDirectory?: Array; - paths?: Array; - resolver?: Config.Path | null; - rootDir?: Config.Path; + paths?: Array; + resolver?: string | null; + rootDir?: string; throwIfNotFound?: boolean; }; export type ResolveModuleConfig = { conditions?: Array; skipNodeResolution?: boolean; - paths?: Array; + paths?: Array; }; const NATIVE_PLATFORM = 'native'; @@ -55,8 +54,8 @@ export default class Resolver { private readonly _options: ResolverConfig; private readonly _moduleMap: IModuleMap; private readonly _moduleIDCache: Map; - private readonly _moduleNameCache: Map; - private readonly _modulePathCache: Map>; + private readonly _moduleNameCache: Map; + private readonly _modulePathCache: Map>; private readonly _supportsNativePlatform: boolean; constructor(moduleMap: IModuleMap, options: ResolverConfig) { @@ -104,9 +103,9 @@ export default class Resolver { } static findNodeModule( - path: Config.Path, + path: string, options: FindNodeModuleConfig, - ): Config.Path | null { + ): string | null { const resolver: typeof defaultResolver = options.resolver ? require(options.resolver) : defaultResolver; @@ -135,10 +134,10 @@ export default class Resolver { static unstable_shouldLoadAsEsm = shouldLoadAsEsm; resolveModuleFromDirIfExists( - dirname: Config.Path, + dirname: string, moduleName: string, options?: ResolveModuleConfig, - ): Config.Path | null { + ): string | null { const paths = options?.paths || this._options.modulePaths; const moduleDirectory = this._options.moduleDirectories; const stringifiedOptions = options ? JSON.stringify(options) : ''; @@ -181,7 +180,7 @@ export default class Resolver { const skipResolution = options && options.skipNodeResolution && !moduleName.includes(path.sep); - const resolveNodeModule = (name: Config.Path, throwIfNotFound = false) => { + const resolveNodeModule = (name: string, throwIfNotFound = false) => { if (this.isCoreModule(name)) { return name; } @@ -230,10 +229,10 @@ export default class Resolver { } resolveModule( - from: Config.Path, + from: string, moduleName: string, options?: ResolveModuleConfig, - ): Config.Path { + ): string { const dirname = path.dirname(from); const module = this.resolveStubModuleName(from, moduleName) || @@ -271,7 +270,7 @@ export default class Resolver { ); } - getModule(name: string): Config.Path | null { + getModule(name: string): string | null { return this._moduleMap.getModule( name, this._options.defaultPlatform, @@ -279,14 +278,14 @@ export default class Resolver { ); } - getModulePath(from: Config.Path, moduleName: string): Config.Path { + getModulePath(from: string, moduleName: string): string { if (moduleName[0] !== '.' || path.isAbsolute(moduleName)) { return moduleName; } return path.normalize(path.dirname(from) + '/' + moduleName); } - getPackage(name: string): Config.Path | null { + getPackage(name: string): string | null { return this._moduleMap.getPackage( name, this._options.defaultPlatform, @@ -294,7 +293,7 @@ export default class Resolver { ); } - getMockModule(from: Config.Path, name: string): Config.Path | null { + getMockModule(from: string, name: string): string | null { const mock = this._moduleMap.getMockModule(name); if (mock) { return mock; @@ -307,7 +306,7 @@ export default class Resolver { return null; } - getModulePaths(from: Config.Path): Array { + getModulePaths(from: string): Array { const cachedModule = this._modulePathCache.get(from); if (cachedModule) { return cachedModule; @@ -325,7 +324,7 @@ export default class Resolver { getModuleID( virtualMocks: Map, - from: Config.Path, + from: string, moduleName = '', options?: ResolveModuleConfig, ): string { @@ -363,10 +362,10 @@ export default class Resolver { private _getAbsolutePath( virtualMocks: Map, - from: Config.Path, + from: string, moduleName: string, options?: ResolveModuleConfig, - ): Config.Path | null { + ): string | null { if (this.isCoreModule(moduleName)) { return moduleName; } @@ -378,10 +377,7 @@ export default class Resolver { : this._getVirtualMockPath(virtualMocks, from, moduleName, options); } - private _getMockPath( - from: Config.Path, - moduleName: string, - ): Config.Path | null { + private _getMockPath(from: string, moduleName: string): string | null { return !this.isCoreModule(moduleName) ? this.getMockModule(from, moduleName) : null; @@ -389,10 +385,10 @@ export default class Resolver { private _getVirtualMockPath( virtualMocks: Map, - from: Config.Path, + from: string, moduleName: string, options?: ResolveModuleConfig, - ): Config.Path { + ): string { const virtualMockPath = this.getModulePath(from, moduleName); return virtualMocks.get(virtualMockPath) ? virtualMockPath @@ -401,16 +397,13 @@ export default class Resolver { : from; } - private _isModuleResolved(from: Config.Path, moduleName: string): boolean { + private _isModuleResolved(from: string, moduleName: string): boolean { return !!( this.getModule(moduleName) || this.getMockModule(from, moduleName) ); } - resolveStubModuleName( - from: Config.Path, - moduleName: string, - ): Config.Path | null { + resolveStubModuleName(from: string, moduleName: string): string | null { const dirname = path.dirname(from); const paths = this._options.modulePaths; const extensions = this._options.extensions.slice(); diff --git a/packages/jest-resolve/src/shouldLoadAsEsm.ts b/packages/jest-resolve/src/shouldLoadAsEsm.ts index aadca23c4d01..f937913a95d5 100644 --- a/packages/jest-resolve/src/shouldLoadAsEsm.ts +++ b/packages/jest-resolve/src/shouldLoadAsEsm.ts @@ -8,7 +8,6 @@ import {dirname, extname} from 'path'; // @ts-expect-error: experimental, not added to the types import {SyntheticModule} from 'vm'; -import type {Config} from '@jest/types'; import {findClosestPackageJson, readPackageCached} from './fileWalkers'; const runtimeSupportsVmModules = typeof SyntheticModule === 'function'; @@ -24,8 +23,8 @@ export function clearCachedLookups(): void { } export default function cachedShouldLoadAsEsm( - path: Config.Path, - extensionsToTreatAsEsm: Array, + path: string, + extensionsToTreatAsEsm: Array, ): boolean { if (!runtimeSupportsVmModules) { return false; @@ -43,8 +42,8 @@ export default function cachedShouldLoadAsEsm( // this is a bad version of what https://github.com/nodejs/modules/issues/393 would provide function shouldLoadAsEsm( - path: Config.Path, - extensionsToTreatAsEsm: Array, + path: string, + extensionsToTreatAsEsm: Array, ): boolean { const extension = extname(path); @@ -72,7 +71,7 @@ function shouldLoadAsEsm( return cachedLookup; } -function cachedPkgCheck(cwd: Config.Path): boolean { +function cachedPkgCheck(cwd: string): boolean { const pkgPath = findClosestPackageJson(cwd); if (!pkgPath) { return false; diff --git a/packages/jest-resolve/src/types.ts b/packages/jest-resolve/src/types.ts index cbe7666ac21f..8469e2b9dc3d 100644 --- a/packages/jest-resolve/src/types.ts +++ b/packages/jest-resolve/src/types.ts @@ -5,18 +5,16 @@ * LICENSE file in the root directory of this source tree. */ -import type {Config} from '@jest/types'; - export type ResolverConfig = { defaultPlatform?: string | null; extensions: Array; hasCoreModules: boolean; moduleDirectories: Array; moduleNameMapper?: Array | null; - modulePaths?: Array; + modulePaths?: Array; platforms?: Array; - resolver?: Config.Path | null; - rootDir: Config.Path; + resolver?: string | null; + rootDir: string; }; type ModuleNameMapperConfig = { diff --git a/packages/jest-resolve/src/utils.ts b/packages/jest-resolve/src/utils.ts index fbbdf19598b8..6a51c4061800 100644 --- a/packages/jest-resolve/src/utils.ts +++ b/packages/jest-resolve/src/utils.ts @@ -7,7 +7,6 @@ import * as path from 'path'; import chalk = require('chalk'); -import type {Config} from '@jest/types'; import {ValidationError} from 'jest-validate'; import Resolver from './resolver'; @@ -19,10 +18,7 @@ const DOCUMENTATION_NOTE = ` ${chalk.bold('Configuration Documentation:')} const createValidationError = (message: string) => new ValidationError(`${BULLET}Validation Error`, message, DOCUMENTATION_NOTE); -const replaceRootDirInPath = ( - rootDir: Config.Path, - filePath: Config.Path, -): string => { +const replaceRootDirInPath = (rootDir: string, filePath: string): string => { if (!/^/.test(filePath)) { return filePath; } @@ -48,7 +44,7 @@ const resolveWithPrefix = ( optionName: string; prefix: string; requireResolveFunction: (moduleName: string) => string; - rootDir: Config.Path; + rootDir: string; }, ): string => { const fileName = replaceRootDirInPath(rootDir, filePath); @@ -98,7 +94,7 @@ export const resolveTestEnvironment = ({ testEnvironment: filePath, requireResolveFunction, }: { - rootDir: Config.Path; + rootDir: string; testEnvironment: string; requireResolveFunction: (moduleName: string) => string; }): string => { @@ -137,7 +133,7 @@ export const resolveWatchPlugin = ( requireResolveFunction, }: { filePath: string; - rootDir: Config.Path; + rootDir: string; requireResolveFunction: (moduleName: string) => string; }, ): string => @@ -166,7 +162,7 @@ export const resolveRunner = ( requireResolveFunction, }: { filePath: string; - rootDir: Config.Path; + rootDir: string; requireResolveFunction: (moduleName: string) => string; }, ): string => @@ -187,7 +183,7 @@ export const resolveSequencer = ( requireResolveFunction, }: { filePath: string; - rootDir: Config.Path; + rootDir: string; requireResolveFunction: (moduleName: string) => string; }, ): string => diff --git a/packages/jest-resolve/tsconfig.json b/packages/jest-resolve/tsconfig.json index c62988ec0d17..33e2660dc928 100644 --- a/packages/jest-resolve/tsconfig.json +++ b/packages/jest-resolve/tsconfig.json @@ -8,7 +8,6 @@ "exclude": ["./**/__mocks__/**/*", "./**/__tests__/**/*"], "references": [ {"path": "../jest-haste-map"}, - {"path": "../jest-types"}, {"path": "../jest-util"}, {"path": "../jest-validate"} ] diff --git a/packages/jest-runner/src/runTest.ts b/packages/jest-runner/src/runTest.ts index 5f16ce755be1..89f9356f8565 100644 --- a/packages/jest-runner/src/runTest.ts +++ b/packages/jest-runner/src/runTest.ts @@ -75,7 +75,7 @@ function freezeConsole( // references to verify if there is a leak, which is not maintainable and error // prone. That's why "runTestInternal" CANNOT be inlined inside "runTest". async function runTestInternal( - path: Config.Path, + path: string, globalConfig: Config.GlobalConfig, config: Config.ProjectConfig, resolver: Resolver, @@ -337,7 +337,7 @@ async function runTestInternal( } export default async function runTest( - path: Config.Path, + path: string, globalConfig: Config.GlobalConfig, config: Config.ProjectConfig, resolver: Resolver, diff --git a/packages/jest-runner/src/testWorker.ts b/packages/jest-runner/src/testWorker.ts index aca3f40c2680..9bf31809b55b 100644 --- a/packages/jest-runner/src/testWorker.ts +++ b/packages/jest-runner/src/testWorker.ts @@ -29,7 +29,7 @@ export type SerializableResolver = { type WorkerData = { config: Config.ProjectConfig; globalConfig: Config.GlobalConfig; - path: Config.Path; + path: string; context?: TestRunnerSerializedContext; }; diff --git a/packages/jest-runner/src/types.ts b/packages/jest-runner/src/types.ts index 47c8194eeb30..4bb5f2c58879 100644 --- a/packages/jest-runner/src/types.ts +++ b/packages/jest-runner/src/types.ts @@ -43,13 +43,13 @@ export type TestRunnerOptions = { // make sure all props here are present in the type below it as well export type TestRunnerContext = { - changedFiles?: Set; - sourcesRelatedToTestsInChangedFiles?: Set; + changedFiles?: Set; + sourcesRelatedToTestsInChangedFiles?: Set; }; export type TestRunnerSerializedContext = { - changedFiles?: Array; - sourcesRelatedToTestsInChangedFiles?: Array; + changedFiles?: Array; + sourcesRelatedToTestsInChangedFiles?: Array; }; // TODO: Should live in `@jest/core` or `jest-watcher` diff --git a/packages/jest-runtime/src/helpers.ts b/packages/jest-runtime/src/helpers.ts index 35af314a7b14..34d9166fcdb8 100644 --- a/packages/jest-runtime/src/helpers.ts +++ b/packages/jest-runtime/src/helpers.ts @@ -31,7 +31,7 @@ export const decodePossibleOutsideJestVmPath = ( export const findSiblingsWithFileExtension = ( moduleFileExtensions: Config.ProjectConfig['moduleFileExtensions'], - from: Config.Path, + from: string, moduleName: string, ): string => { if (!path.isAbsolute(moduleName) && path.extname(moduleName) === '') { diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index 368384b3e51c..363eef8f90cb 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -204,10 +204,10 @@ export default class Runtime { private readonly _moduleMocker: ModuleMocker; private _isolatedModuleRegistry: ModuleRegistry | null; private _moduleRegistry: ModuleRegistry; - private readonly _esmoduleRegistry: Map; - private readonly _cjsNamedExports: Map>; + private readonly _esmoduleRegistry: Map; + private readonly _cjsNamedExports: Map>; private readonly _esmModuleLinkingMap: WeakMap>; - private readonly _testPath: Config.Path; + private readonly _testPath: string; private readonly _resolver: Resolver; private _shouldAutoMock: boolean; private readonly _shouldMockModuleCache: Map; @@ -239,7 +239,7 @@ export default class Runtime { transformer: ScriptTransformer, cacheFS: Map, coverageOptions: ShouldInstrumentOptions, - testPath: Config.Path, + testPath: string, ) { this._cacheFS = cacheFS; this._config = config; @@ -421,7 +421,7 @@ export default class Runtime { } // unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it - unstable_shouldLoadAsEsm(path: Config.Path): boolean { + unstable_shouldLoadAsEsm(path: string): boolean { return Resolver.unstable_shouldLoadAsEsm( path, this._config.extensionsToTreatAsEsm, @@ -430,7 +430,7 @@ export default class Runtime { // not async _now_, but transform will be private async loadEsmModule( - modulePath: Config.Path, + modulePath: string, query = '', ): Promise { const cacheKey = modulePath + query; @@ -703,7 +703,7 @@ export default class Runtime { } async unstable_importModule( - from: Config.Path, + from: string, moduleName?: string, ): Promise { invariant( @@ -722,11 +722,7 @@ export default class Runtime { return this.linkAndEvaluateModule(module); } - private loadCjsAsEsm( - from: Config.Path, - modulePath: Config.Path, - context: VMContext, - ) { + private loadCjsAsEsm(from: string, modulePath: string, context: VMContext) { // CJS loaded via `import` should share cache with other CJS: https://github.com/nodejs/modules/issues/503 const cjs = this.requireModuleOrMock(from, modulePath); @@ -757,7 +753,7 @@ export default class Runtime { } private async importMock( - from: Config.Path, + from: string, moduleName: string, context: VMContext, ): Promise { @@ -797,7 +793,7 @@ export default class Runtime { throw new Error('Attempting to import a mock without a factory'); } - private getExportsOfCjs(modulePath: Config.Path) { + private getExportsOfCjs(modulePath: string) { const cachedNamedExports = this._cjsNamedExports.get(modulePath); if (cachedNamedExports) { @@ -827,7 +823,7 @@ export default class Runtime { } requireModule( - from: Config.Path, + from: string, moduleName?: string, options?: InternalModuleOptions, isRequireActual = false, @@ -927,7 +923,7 @@ export default class Runtime { return localModule.exports; } - requireInternalModule(from: Config.Path, to?: string): T { + requireInternalModule(from: string, to?: string): T { if (to) { const require = ( nativeModule.createRequire ?? nativeModule.createRequireFromPath @@ -950,11 +946,11 @@ export default class Runtime { }); } - requireActual(from: Config.Path, moduleName: string): T { + requireActual(from: string, moduleName: string): T { return this.requireModule(from, moduleName, undefined, true); } - requireMock(from: Config.Path, moduleName: string): T { + requireMock(from: string, moduleName: string): T { const moduleID = this._resolver.getModuleID( this._virtualMocks, from, @@ -1041,9 +1037,9 @@ export default class Runtime { private _loadModule( localModule: InitialModule, - from: Config.Path, + from: string, moduleName: string | undefined, - modulePath: Config.Path, + modulePath: string, options: InternalModuleOptions | undefined, moduleRegistry: ModuleRegistry, ) { @@ -1077,7 +1073,7 @@ export default class Runtime { }; } - requireModuleOrMock(from: Config.Path, moduleName: string): T { + requireModuleOrMock(from: string, moduleName: string): T { // this module is unmockable if (moduleName === '@jest/globals') { // @ts-expect-error: we don't care that it's not assignable to T @@ -1305,7 +1301,7 @@ export default class Runtime { } private _resolveModule( - from: Config.Path, + from: string, to: string | undefined, options?: ResolveModuleConfig, ) { @@ -1313,7 +1309,7 @@ export default class Runtime { } private _requireResolve( - from: Config.Path, + from: string, moduleName?: string, options: ResolveOptions = {}, ) { @@ -1371,7 +1367,7 @@ export default class Runtime { } } - private _requireResolvePaths(from: Config.Path, moduleName?: string) { + private _requireResolvePaths(from: string, moduleName?: string) { if (moduleName == null) { throw new Error( 'The first argument to require.resolve.paths must be a string. Received null or undefined.', @@ -1396,7 +1392,7 @@ export default class Runtime { localModule: InitialModule, options: InternalModuleOptions | undefined, moduleRegistry: ModuleRegistry, - from: Config.Path | null, + from: string | null, ) { if (this.isTornDown) { this._logFormattedReferenceError( @@ -1721,7 +1717,7 @@ export default class Runtime { return Module; } - private _generateMock(from: Config.Path, moduleName: string) { + private _generateMock(from: string, moduleName: string) { const modulePath = this._resolver.resolveStubModuleName(from, moduleName) || this._resolveModule(from, moduleName, {conditions: this.cjsConditions}); @@ -1765,7 +1761,7 @@ export default class Runtime { } private _shouldMock( - from: Config.Path, + from: string, moduleName: string, explicitShouldMock: Map, options: ResolveModuleConfig, @@ -1893,7 +1889,7 @@ export default class Runtime { return moduleRequire; } - private _createJestObjectFor(from: Config.Path): Jest { + private _createJestObjectFor(from: string): Jest { const disableAutomock = () => { this._shouldAutoMock = false; return jestObject; @@ -2161,7 +2157,7 @@ export default class Runtime { throw e; } - private getGlobalsForCjs(from: Config.Path): JestGlobalsWithJest { + private getGlobalsForCjs(from: string): JestGlobalsWithJest { const jest = this.jestObjectCaches.get(from); invariant(jest, 'There should always be a Jest object already'); @@ -2170,7 +2166,7 @@ export default class Runtime { } private getGlobalsForEsm( - from: Config.Path, + from: string, context: VMContext, ): Promise { let jest = this.jestObjectCaches.get(from); @@ -2222,7 +2218,7 @@ export default class Runtime { }; } - private readFile(filename: Config.Path): string { + private readFile(filename: string): string { let source = this._cacheFS.get(filename); if (!source) { diff --git a/packages/jest-serializer/src/index.ts b/packages/jest-serializer/src/index.ts index 7fc660a34909..62ae49c41e4f 100644 --- a/packages/jest-serializer/src/index.ts +++ b/packages/jest-serializer/src/index.ts @@ -8,8 +8,6 @@ import {deserialize as v8Deserialize, serialize as v8Serialize} from 'v8'; import * as fs from 'graceful-fs'; -type Path = string; - // JSON and V8 serializers are both stable when it comes to compatibility. The // current JSON specification is well defined in RFC 8259, and V8 ensures that // the versions are compatible by encoding the serialization version in the own @@ -27,11 +25,11 @@ export function serialize(content: unknown): Buffer { // Synchronous filesystem functions. -export function readFileSync(filePath: Path): unknown { +export function readFileSync(filePath: string): unknown { return v8Deserialize(fs.readFileSync(filePath)); } -export function writeFileSync(filePath: Path, content: unknown): void { +export function writeFileSync(filePath: string, content: unknown): void { return fs.writeFileSync(filePath, v8Serialize(content)); } diff --git a/packages/jest-snapshot/src/InlineSnapshots.ts b/packages/jest-snapshot/src/InlineSnapshots.ts index 7d2d8ec3b17b..4f1310528f47 100644 --- a/packages/jest-snapshot/src/InlineSnapshots.ts +++ b/packages/jest-snapshot/src/InlineSnapshots.ts @@ -14,7 +14,6 @@ import type { BuiltInParserName as PrettierParserName, } from 'prettier'; import semver = require('semver'); -import type {Config} from '@jest/types'; import type {Frame} from 'jest-message-util'; import {escapeBacktickString} from './utils'; @@ -47,7 +46,7 @@ export type InlineSnapshot = { export function saveInlineSnapshots( snapshots: Array, - prettierPath: Config.Path, + prettierPath: string, ): void { let prettier: Prettier | null = null; if (prettierPath) { @@ -72,7 +71,7 @@ export function saveInlineSnapshots( const saveSnapshotsForFile = ( snapshots: Array, - sourceFilePath: Config.Path, + sourceFilePath: string, prettier?: Prettier, ) => { const sourceFile = fs.readFileSync(sourceFilePath, 'utf8'); @@ -362,7 +361,7 @@ const createFormattingParser = return ast; }; -const simpleDetectParser = (filePath: Config.Path): PrettierParserName => { +const simpleDetectParser = (filePath: string): PrettierParserName => { const extname = path.extname(filePath); if (/\.tsx?$/.test(extname)) { return 'typescript'; diff --git a/packages/jest-snapshot/src/SnapshotResolver.ts b/packages/jest-snapshot/src/SnapshotResolver.ts index 5e8358e5046d..7c55b4ef7a9b 100644 --- a/packages/jest-snapshot/src/SnapshotResolver.ts +++ b/packages/jest-snapshot/src/SnapshotResolver.ts @@ -13,8 +13,8 @@ import {interopRequireDefault} from 'jest-util'; export type SnapshotResolver = { testPathForConsistencyCheck: string; - resolveSnapshotPath(testPath: Config.Path, extension?: string): Config.Path; - resolveTestPath(snapshotPath: Config.Path, extension?: string): Config.Path; + resolveSnapshotPath(testPath: string, extension?: string): string; + resolveTestPath(snapshotPath: string, extension?: string): string; }; export const EXTENSION = 'snap'; @@ -23,7 +23,7 @@ export const DOT_EXTENSION = '.' + EXTENSION; export const isSnapshotPath = (path: string): boolean => path.endsWith(DOT_EXTENSION); -const cache = new Map(); +const cache = new Map(); type LocalRequire = (module: string) => unknown; @@ -46,7 +46,7 @@ export const buildSnapshotResolver = async ( async function createSnapshotResolver( localRequire: LocalRequire, - snapshotResolverPath?: Config.Path | null, + snapshotResolverPath?: string | null, ): Promise { return typeof snapshotResolverPath === 'string' ? await createCustomSnapshotResolver(snapshotResolverPath, localRequire) @@ -55,13 +55,13 @@ async function createSnapshotResolver( function createDefaultSnapshotResolver(): SnapshotResolver { return { - resolveSnapshotPath: (testPath: Config.Path) => + resolveSnapshotPath: (testPath: string) => path.join( path.join(path.dirname(testPath), '__snapshots__'), path.basename(testPath) + DOT_EXTENSION, ), - resolveTestPath: (snapshotPath: Config.Path) => + resolveTestPath: (snapshotPath: string) => path.resolve( path.dirname(snapshotPath), '..', @@ -77,7 +77,7 @@ function createDefaultSnapshotResolver(): SnapshotResolver { } async function createCustomSnapshotResolver( - snapshotResolverPath: Config.Path, + snapshotResolverPath: string, localRequire: LocalRequire, ): Promise { const custom: SnapshotResolver = interopRequireDefault( @@ -96,9 +96,9 @@ async function createCustomSnapshotResolver( }); const customResolver = { - resolveSnapshotPath: (testPath: Config.Path) => + resolveSnapshotPath: (testPath: string) => custom.resolveSnapshotPath(testPath, DOT_EXTENSION), - resolveTestPath: (snapshotPath: Config.Path) => + resolveTestPath: (snapshotPath: string) => custom.resolveTestPath(snapshotPath, DOT_EXTENSION), testPathForConsistencyCheck: custom.testPathForConsistencyCheck, }; diff --git a/packages/jest-snapshot/src/State.ts b/packages/jest-snapshot/src/State.ts index 26025c83bb80..fc96a3b47add 100644 --- a/packages/jest-snapshot/src/State.ts +++ b/packages/jest-snapshot/src/State.ts @@ -24,7 +24,7 @@ import { export type SnapshotStateOptions = { updateSnapshot: Config.SnapshotUpdateState; - prettierPath: Config.Path; + prettierPath: string; expand?: boolean; snapshotFormat: PrettyFormatOptions; }; @@ -59,10 +59,10 @@ export default class SnapshotState { private _updateSnapshot: Config.SnapshotUpdateState; private _snapshotData: SnapshotData; private _initialData: SnapshotData; - private _snapshotPath: Config.Path; + private _snapshotPath: string; private _inlineSnapshots: Array; private _uncheckedKeys: Set; - private _prettierPath: Config.Path; + private _prettierPath: string; private _snapshotFormat: PrettyFormatOptions; added: number; @@ -71,7 +71,7 @@ export default class SnapshotState { unmatched: number; updated: number; - constructor(snapshotPath: Config.Path, options: SnapshotStateOptions) { + constructor(snapshotPath: string, options: SnapshotStateOptions) { this._snapshotPath = snapshotPath; const {data, dirty} = getSnapshotData( this._snapshotPath, diff --git a/packages/jest-snapshot/src/index.ts b/packages/jest-snapshot/src/index.ts index 5af2cbdf69e7..c0e229e257b1 100644 --- a/packages/jest-snapshot/src/index.ts +++ b/packages/jest-snapshot/src/index.ts @@ -113,7 +113,7 @@ function stripAddedIndentation(inlineSnapshot: string) { return inlineSnapshot; } -const fileExists = (filePath: Config.Path, hasteFS: HasteFS): boolean => +const fileExists = (filePath: string, hasteFS: HasteFS): boolean => hasteFS.exists(filePath) || fs.existsSync(filePath); export const cleanup = ( @@ -158,8 +158,8 @@ export const cleanup = ( export const toMatchSnapshot: MatcherFunctionWithState = function ( received: unknown, - propertiesOrHint?: object | Config.Path, - hint?: Config.Path, + propertiesOrHint?: object | string, + hint?: string, ) { const matcherName = 'toMatchSnapshot'; let properties; diff --git a/packages/jest-snapshot/src/utils.ts b/packages/jest-snapshot/src/utils.ts index 1f1175875175..0632654ec856 100644 --- a/packages/jest-snapshot/src/utils.ts +++ b/packages/jest-snapshot/src/utils.ts @@ -80,7 +80,7 @@ function isObject(item: unknown): boolean { return item != null && typeof item === 'object' && !Array.isArray(item); } -export const testNameToKey = (testName: Config.Path, count: number): string => +export const testNameToKey = (testName: string, count: number): string => testName + ' ' + count; export const keyToTestName = (key: string): string => { @@ -92,7 +92,7 @@ export const keyToTestName = (key: string): string => { }; export const getSnapshotData = ( - snapshotPath: Config.Path, + snapshotPath: string, update: Config.SnapshotUpdateState, ): { data: SnapshotData; @@ -188,7 +188,7 @@ export const escapeBacktickString = (str: string): string => const printBacktickString = (str: string): string => '`' + escapeBacktickString(str) + '`'; -export const ensureDirectoryExists = (filePath: Config.Path): void => { +export const ensureDirectoryExists = (filePath: string): void => { try { fs.mkdirSync(path.join(path.dirname(filePath)), {recursive: true}); } catch {} @@ -198,7 +198,7 @@ const normalizeNewlines = (string: string) => string.replace(/\r\n|\r/g, '\n'); export const saveSnapshotFile = ( snapshotData: SnapshotData, - snapshotPath: Config.Path, + snapshotPath: string, ): void => { const snapshots = Object.keys(snapshotData) .sort(naturalCompare) diff --git a/packages/jest-test-result/src/helpers.ts b/packages/jest-test-result/src/helpers.ts index a749a8c33d53..539e51d247d8 100644 --- a/packages/jest-test-result/src/helpers.ts +++ b/packages/jest-test-result/src/helpers.ts @@ -5,7 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -import type {Config} from '@jest/types'; import type {AggregatedResult, SerializableError, TestResult} from './types'; export const makeEmptyAggregatedTestResult = (): AggregatedResult => ({ @@ -44,7 +43,7 @@ export const makeEmptyAggregatedTestResult = (): AggregatedResult => ({ }); export const buildFailureTestResult = ( - testPath: Config.Path, + testPath: string, err: SerializableError, ): TestResult => ({ console: undefined, diff --git a/packages/jest-test-result/src/types.ts b/packages/jest-test-result/src/types.ts index d911ac818fbf..fafefa4981e1 100644 --- a/packages/jest-test-result/src/types.ts +++ b/packages/jest-test-result/src/types.ts @@ -119,7 +119,7 @@ export type TestResult = { updated: number; }; testExecError?: SerializableError; - testFilePath: Config.Path; + testFilePath: string; testResults: Array; v8Coverage?: V8CoverageResult; }; @@ -185,7 +185,7 @@ export type SnapshotSummary = { export type Test = { context: Context; duration?: number; - path: Config.Path; + path: string; }; type Context = { @@ -200,7 +200,7 @@ export type TestEvents = { 'test-file-start': [Test]; 'test-file-success': [Test, TestResult]; 'test-file-failure': [Test, SerializableError]; - 'test-case-result': [Config.Path, AssertionResult]; + 'test-case-result': [string, AssertionResult]; }; export type TestFileEvent = ( diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index 7e17f65822e5..3b762945035a 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -75,7 +75,7 @@ async function waitForPromiseWithCleanup( class ScriptTransformer { private readonly _cache: ProjectCache; private readonly _transformCache = new Map< - Config.Path, + string, {transformer: Transformer; transformerConfig: unknown} >(); private _transformsAreLoaded = false; @@ -103,7 +103,7 @@ class ScriptTransformer { private _buildCacheKeyFromFileInfo( fileData: string, - filename: Config.Path, + filename: string, transformOptions: TransformOptions, transformerCacheKey: string | undefined, ): string { @@ -125,7 +125,7 @@ class ScriptTransformer { private _getCacheKey( fileData: string, - filename: Config.Path, + filename: string, options: ReducedTransformOptions, ): string { const configString = this._cache.configString; @@ -159,7 +159,7 @@ class ScriptTransformer { private async _getCacheKeyAsync( fileData: string, - filename: Config.Path, + filename: string, options: ReducedTransformOptions, ): Promise { const configString = this._cache.configString; @@ -197,9 +197,9 @@ class ScriptTransformer { } private _createFolderFromCacheKey( - filename: Config.Path, + filename: string, cacheKey: string, - ): Config.Path { + ): string { const HasteMapClass = HasteMap.getStatic(this._config); const baseCacheDir = HasteMapClass.getCacheFilePath( this._config.cacheDirectory, @@ -221,26 +221,26 @@ class ScriptTransformer { } private _getFileCachePath( - filename: Config.Path, + filename: string, content: string, options: ReducedTransformOptions, - ): Config.Path { + ): string { const cacheKey = this._getCacheKey(content, filename, options); return this._createFolderFromCacheKey(filename, cacheKey); } private async _getFileCachePathAsync( - filename: Config.Path, + filename: string, content: string, options: ReducedTransformOptions, - ): Promise { + ): Promise { const cacheKey = await this._getCacheKeyAsync(content, filename, options); return this._createFolderFromCacheKey(filename, cacheKey); } - private _getTransformPath(filename: Config.Path) { + private _getTransformPath(filename: string) { const transformRegExp = this._cache.transformRegExp; if (!transformRegExp) { return undefined; @@ -284,7 +284,7 @@ class ScriptTransformer { this._transformsAreLoaded = true; } - private _getTransformer(filename: Config.Path) { + private _getTransformer(filename: string) { if (!this._transformsAreLoaded) { throw new Error( 'Jest: Transformers have not been loaded yet - make sure to run `loadTransformers` and wait for it to complete before starting to transform files', @@ -312,7 +312,7 @@ class ScriptTransformer { } private _instrumentFile( - filename: Config.Path, + filename: string, input: TransformedSource, canMapToInput: boolean, options: ReducedTransformOptions, @@ -364,7 +364,7 @@ class ScriptTransformer { shouldCallTransform: boolean, options: ReducedTransformOptions, processed: TransformedSource | null, - sourceMapPath: Config.Path | null, + sourceMapPath: string | null, ): TransformResult { let transformed: TransformedSource = { code: content, @@ -452,7 +452,7 @@ class ScriptTransformer { } transformSource( - filepath: Config.Path, + filepath: string, content: string, options: ReducedTransformOptions, ): TransformResult { @@ -460,7 +460,7 @@ class ScriptTransformer { const {transformer, transformerConfig = {}} = this._getTransformer(filename) || {}; const cacheFilePath = this._getFileCachePath(filename, content, options); - const sourceMapPath: Config.Path = cacheFilePath + '.map'; + const sourceMapPath: string = cacheFilePath + '.map'; // Ignore cache if `config.cache` is set (--no-cache) const code = this._config.cache ? readCodeCacheFile(cacheFilePath) : null; @@ -507,7 +507,7 @@ class ScriptTransformer { } async transformSourceAsync( - filepath: Config.Path, + filepath: string, content: string, options: ReducedTransformOptions, ): Promise { @@ -519,7 +519,7 @@ class ScriptTransformer { content, options, ); - const sourceMapPath: Config.Path = cacheFilePath + '.map'; + const sourceMapPath: string = cacheFilePath + '.map'; // Ignore cache if `config.cache` is set (--no-cache) const code = this._config.cache ? readCodeCacheFile(cacheFilePath) : null; @@ -571,7 +571,7 @@ class ScriptTransformer { } private async _transformAndBuildScriptAsync( - filename: Config.Path, + filename: string, options: Options, transformOptions: ReducedTransformOptions, fileSource?: string, @@ -614,7 +614,7 @@ class ScriptTransformer { } private _transformAndBuildScript( - filename: Config.Path, + filename: string, options: Options, transformOptions: ReducedTransformOptions, fileSource?: string, @@ -657,7 +657,7 @@ class ScriptTransformer { } async transformAsync( - filename: Config.Path, + filename: string, options: Options, fileSource?: string, ): Promise { @@ -685,7 +685,7 @@ class ScriptTransformer { } transform( - filename: Config.Path, + filename: string, options: Options, fileSource?: string, ): TransformResult { @@ -714,7 +714,7 @@ class ScriptTransformer { } transformJson( - filename: Config.Path, + filename: string, options: Options, fileSource: string, ): string { @@ -796,7 +796,7 @@ class ScriptTransformer { } } - shouldTransform(filename: Config.Path): boolean { + shouldTransform(filename: string): boolean { const ignoreRegexp = this._cache.ignorePatternsRegExp; const isIgnored = ignoreRegexp ? ignoreRegexp.test(filename) : false; @@ -837,7 +837,7 @@ export async function createTranspilingRequire( }; } -const removeFile = (path: Config.Path) => { +const removeFile = (path: string) => { try { fs.unlinkSync(path); } catch {} @@ -860,7 +860,7 @@ const stripShebang = (content: string) => { * it right away. This is not a great system, because source map cache file * could get corrupted, out-of-sync, etc. */ -function writeCodeCacheFile(cachePath: Config.Path, code: string) { +function writeCodeCacheFile(cachePath: string, code: string) { const checksum = createHash('md5').update(code).digest('hex'); writeCacheFile(cachePath, checksum + '\n' + code); } @@ -871,7 +871,7 @@ function writeCodeCacheFile(cachePath: Config.Path, code: string) { * could happen if an older version of `jest-runtime` writes non-atomically to * the same cache, for example. */ -function readCodeCacheFile(cachePath: Config.Path): string | null { +function readCodeCacheFile(cachePath: string): string | null { const content = readCacheFile(cachePath); if (content == null) { return null; @@ -890,7 +890,7 @@ function readCodeCacheFile(cachePath: Config.Path): string | null { * two processes to write to the same file at the same time. It also reduces * the risk of reading a file that's being overwritten at the same time. */ -const writeCacheFile = (cachePath: Config.Path, fileData: string) => { +const writeCacheFile = (cachePath: string, fileData: string) => { try { writeFileAtomic(cachePath, fileData, {encoding: 'utf8', fsync: false}); } catch (e: any) { @@ -916,13 +916,13 @@ const writeCacheFile = (cachePath: Config.Path, fileData: string) => { */ const cacheWriteErrorSafeToIgnore = ( e: Error & {code: string}, - cachePath: Config.Path, + cachePath: string, ) => process.platform === 'win32' && e.code === 'EPERM' && fs.existsSync(cachePath); -const readCacheFile = (cachePath: Config.Path): string | null => { +const readCacheFile = (cachePath: string): string | null => { if (!fs.existsSync(cachePath)) { return null; } @@ -948,7 +948,7 @@ const readCacheFile = (cachePath: Config.Path): string | null => { return fileData; }; -const getScriptCacheKey = (filename: Config.Path, instrument: boolean) => { +const getScriptCacheKey = (filename: string, instrument: boolean) => { const mtime = fs.statSync(filename).mtime; return filename + '_' + mtime.getTime() + (instrument ? '_instrumented' : ''); }; diff --git a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts index ecf2832d892b..eca75374ea38 100644 --- a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts +++ b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts @@ -210,7 +210,7 @@ jest.mock( ); const getCachePath = ( - mockFs: Record, + mockFs: Record, config: Config.ProjectConfig, ) => { for (const path in mockFs) { @@ -224,7 +224,7 @@ const getCachePath = ( let createScriptTransformer: typeof import('../ScriptTransformer').createScriptTransformer; let config: Config.ProjectConfig; let fs: typeof import('fs'); -let mockFs: Record; +let mockFs: Record; let object: (input: T) => T; let writeFileAtomic: typeof import('write-file-atomic'); diff --git a/packages/jest-transform/src/shouldInstrument.ts b/packages/jest-transform/src/shouldInstrument.ts index a876bf4676e6..4587e388a7f4 100644 --- a/packages/jest-transform/src/shouldInstrument.ts +++ b/packages/jest-transform/src/shouldInstrument.ts @@ -31,7 +31,7 @@ const getRegex = (regexStr: string) => { }; export default function shouldInstrument( - filename: Config.Path, + filename: string, options: ShouldInstrumentOptions, config: Config.ProjectConfig, ): boolean { diff --git a/packages/jest-transform/src/types.ts b/packages/jest-transform/src/types.ts index 0e0753c0eb1b..1d28cbdb30ea 100644 --- a/packages/jest-transform/src/types.ts +++ b/packages/jest-transform/src/types.ts @@ -16,8 +16,8 @@ export interface ShouldInstrumentOptions | 'collectCoverageOnlyFrom' | 'coverageProvider' > { - changedFiles?: Set; - sourcesRelatedToTestsInChangedFiles?: Set; + changedFiles?: Set; + sourcesRelatedToTestsInChangedFiles?: Set; } export interface Options @@ -80,25 +80,25 @@ export interface SyncTransformer { getCacheKey?: ( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, options: TransformOptions, ) => string; getCacheKeyAsync?: ( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, options: TransformOptions, ) => Promise; process: ( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, options: TransformOptions, ) => TransformedSource; processAsync?: ( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, options: TransformOptions, ) => Promise; } @@ -115,25 +115,25 @@ export interface AsyncTransformer { getCacheKey?: ( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, options: TransformOptions, ) => string; getCacheKeyAsync?: ( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, options: TransformOptions, ) => Promise; process?: ( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, options: TransformOptions, ) => TransformedSource; processAsync: ( sourceText: string, - sourcePath: Config.Path, + sourcePath: string, options: TransformOptions, ) => Promise; } diff --git a/packages/jest-types/src/Config.ts b/packages/jest-types/src/Config.ts index c35af9220496..bc1c15daa969 100644 --- a/packages/jest-types/src/Config.ts +++ b/packages/jest-types/src/Config.ts @@ -14,10 +14,6 @@ type CoverageProvider = 'babel' | 'v8'; type Timers = 'real' | 'fake' | 'modern' | 'legacy'; -export type Path = string; - -export type Glob = string; - export type HasteConfig = { /** Whether to hash files using SHA-1. */ computeSha1?: boolean; @@ -31,7 +27,7 @@ export type HasteConfig = { * Projects with `watchman` set to true will error if this option is set to true. */ enableSymlinks?: boolean; - /** Path to a custom implementation of Haste. */ + /** string to a custom implementation of Haste. */ hasteImplModulePath?: string; /** All platforms to target, e.g ['ios', 'android']. */ platforms?: Array; @@ -65,7 +61,7 @@ export type DefaultOptions = { automock: boolean; bail: number; cache: boolean; - cacheDirectory: Path; + cacheDirectory: string; changedFilesWithAncestor: boolean; ci: boolean; clearMocks: boolean; @@ -77,8 +73,8 @@ export type DefaultOptions = { detectOpenHandles: boolean; errorOnDeprecated: boolean; expand: boolean; - extensionsToTreatAsEsm: Array; - forceCoverageMatch: Array; + extensionsToTreatAsEsm: Array; + forceCoverageMatch: Array; globals: ConfigGlobals; haste: HasteConfig; injectGlobals: boolean; @@ -97,26 +93,26 @@ export type DefaultOptions = { resetMocks: boolean; resetModules: boolean; restoreMocks: boolean; - roots: Array; + roots: Array; runTestsByPath: boolean; runner: string; - setupFiles: Array; - setupFilesAfterEnv: Array; + setupFiles: Array; + setupFilesAfterEnv: Array; skipFilter: boolean; slowTestThreshold: number; - snapshotSerializers: Array; + snapshotSerializers: Array; testEnvironment: string; testEnvironmentOptions: Record; testFailureExitCode: string | number; testLocationInResults: boolean; - testMatch: Array; + testMatch: Array; testPathIgnorePatterns: Array; testRegex: Array; testRunner: string; testSequencer: string; testURL: string; timers: Timers; - transformIgnorePatterns: Array; + transformIgnorePatterns: Array; useStderr: boolean; watch: boolean; watchPathIgnorePatterns: Array; @@ -140,13 +136,13 @@ export type InitialOptions = Partial<{ automock: boolean; bail: boolean | number; cache: boolean; - cacheDirectory: Path; + cacheDirectory: string; ci: boolean; clearMocks: boolean; changedFilesWithAncestor: boolean; changedSince: string; collectCoverage: boolean; - collectCoverageFrom: Array; + collectCoverageFrom: Array; collectCoverageOnlyFrom: { [key: string]: boolean; }; @@ -160,11 +156,11 @@ export type InitialOptions = Partial<{ detectOpenHandles: boolean; displayName: string | DisplayName; expand: boolean; - extensionsToTreatAsEsm: Array; + extensionsToTreatAsEsm: Array; extraGlobals: Array; - filter: Path; + filter: string; findRelatedTests: boolean; - forceCoverageMatch: Array; + forceCoverageMatch: Array; forceExit: boolean; json: boolean; globals: ConfigGlobals; @@ -180,7 +176,7 @@ export type InitialOptions = Partial<{ maxWorkers: number | string; moduleDirectories: Array; moduleFileExtensions: Array; - moduleLoader: Path; + moduleLoader: string; moduleNameMapper: { [key: string]: string | Array; }; @@ -192,52 +188,52 @@ export type InitialOptions = Partial<{ notifyMode: string; onlyChanged: boolean; onlyFailures: boolean; - outputFile: Path; + outputFile: string; passWithNoTests: boolean; /** * @deprecated Use `transformIgnorePatterns` options instead. */ - preprocessorIgnorePatterns: Array; + preprocessorIgnorePatterns: Array; preset: string | null | undefined; prettierPath: string | null | undefined; - projects: Array; + projects: Array; replname: string | null | undefined; resetMocks: boolean; resetModules: boolean; - resolver: Path | null | undefined; + resolver: string | null | undefined; restoreMocks: boolean; - rootDir: Path; - roots: Array; + rootDir: string; + roots: Array; runner: string; runTestsByPath: boolean; /** * @deprecated Use `transform` options instead. */ scriptPreprocessor: string; - setupFiles: Array; + setupFiles: Array; /** * @deprecated Use `setupFilesAfterEnv` options instead. */ - setupTestFrameworkScriptFile: Path; - setupFilesAfterEnv: Array; + setupTestFrameworkScriptFile: string; + setupFilesAfterEnv: Array; silent: boolean; skipFilter: boolean; skipNodeResolution: boolean; slowTestThreshold: number; - snapshotResolver: Path; - snapshotSerializers: Array; + snapshotResolver: string; + snapshotSerializers: Array; snapshotFormat: SnapshotFormat; errorOnDeprecated: boolean; testEnvironment: string; testEnvironmentOptions: Record; testFailureExitCode: string | number; testLocationInResults: boolean; - testMatch: Array; + testMatch: Array; testNamePattern: string; /** * @deprecated Use `roots` options instead. */ - testPathDirs: Array; + testPathDirs: Array; testPathIgnorePatterns: Array; testRegex: string | Array; testResultsProcessor: string; @@ -247,9 +243,9 @@ export type InitialOptions = Partial<{ testTimeout: number; timers: Timers; transform: { - [regex: string]: Path | TransformerConfig; + [regex: string]: string | TransformerConfig; }; - transformIgnorePatterns: Array; + transformIgnorePatterns: Array; watchPathIgnorePatterns: Array; unmockedModulePathPatterns: Array; updateSnapshot: boolean; @@ -289,7 +285,7 @@ export type GlobalConfig = { changedFilesWithAncestor: boolean; ci: boolean; collectCoverage: boolean; - collectCoverageFrom: Array; + collectCoverageFrom: Array; collectCoverageOnlyFrom?: { [key: string]: boolean; }; @@ -301,7 +297,7 @@ export type GlobalConfig = { detectLeaks: boolean; detectOpenHandles: boolean; expand: boolean; - filter?: Path; + filter?: string; findRelatedTests: boolean; forceExit: boolean; json: boolean; @@ -317,15 +313,15 @@ export type GlobalConfig = { noSCM?: boolean; notify: boolean; notifyMode: NotifyMode; - outputFile?: Path; + outputFile?: string; onlyChanged: boolean; onlyFailures: boolean; passWithNoTests: boolean; - projects: Array; + projects: Array; replname?: string; reporters?: Array; runTestsByPath: boolean; - rootDir: Path; + rootDir: string; silent?: boolean; skipFilter: boolean; snapshotFormat: SnapshotFormat; @@ -351,19 +347,19 @@ export type GlobalConfig = { export type ProjectConfig = { automock: boolean; cache: boolean; - cacheDirectory: Path; + cacheDirectory: string; clearMocks: boolean; coveragePathIgnorePatterns: Array; - cwd: Path; + cwd: string; dependencyExtractor?: string; detectLeaks: boolean; detectOpenHandles: boolean; displayName?: DisplayName; errorOnDeprecated: boolean; - extensionsToTreatAsEsm: Array; + extensionsToTreatAsEsm: Array; extraGlobals: Array; - filter?: Path; - forceCoverageMatch: Array; + filter?: string; + forceCoverageMatch: Array; globalSetup?: string; globalTeardown?: string; globals: ConfigGlobals; @@ -371,7 +367,7 @@ export type ProjectConfig = { injectGlobals: boolean; moduleDirectories: Array; moduleFileExtensions: Array; - moduleLoader?: Path; + moduleLoader?: string; moduleNameMapper: Array<[string, string]>; modulePathIgnorePatterns: Array; modulePaths?: Array; @@ -379,30 +375,30 @@ export type ProjectConfig = { prettierPath: string; resetMocks: boolean; resetModules: boolean; - resolver?: Path; + resolver?: string; restoreMocks: boolean; - rootDir: Path; - roots: Array; + rootDir: string; + roots: Array; runner: string; - setupFiles: Array; - setupFilesAfterEnv: Array; + setupFiles: Array; + setupFilesAfterEnv: Array; skipFilter: boolean; skipNodeResolution?: boolean; slowTestThreshold: number; - snapshotResolver?: Path; - snapshotSerializers: Array; + snapshotResolver?: string; + snapshotSerializers: Array; snapshotFormat: SnapshotFormat; testEnvironment: string; testEnvironmentOptions: Record; - testMatch: Array; + testMatch: Array; testLocationInResults: boolean; testPathIgnorePatterns: Array; testRegex: Array; testRunner: string; testURL: string; timers: Timers; - transform: Array<[string, Path, Record]>; - transformIgnorePatterns: Array; + transform: Array<[string, string, Record]>; + transformIgnorePatterns: Array; watchPathIgnorePatterns: Array; unmockedModulePathPatterns?: Array; }; diff --git a/packages/jest-util/src/createDirectory.ts b/packages/jest-util/src/createDirectory.ts index e02a2f278818..6e010e3110d7 100644 --- a/packages/jest-util/src/createDirectory.ts +++ b/packages/jest-util/src/createDirectory.ts @@ -6,9 +6,8 @@ */ import * as fs from 'graceful-fs'; -import type {Config} from '@jest/types'; -export default function createDirectory(path: Config.Path): void { +export default function createDirectory(path: string): void { try { fs.mkdirSync(path, {recursive: true}); } catch (e: any) { diff --git a/packages/jest-util/src/globsToMatcher.ts b/packages/jest-util/src/globsToMatcher.ts index ceb8d62c3f07..4caa27455cc2 100644 --- a/packages/jest-util/src/globsToMatcher.ts +++ b/packages/jest-util/src/globsToMatcher.ts @@ -6,10 +6,9 @@ */ import picomatch = require('picomatch'); -import type {Config} from '@jest/types'; import replacePathSepForGlob from './replacePathSepForGlob'; -type Matcher = (str: Config.Path) => boolean; +type Matcher = (str: string) => boolean; const globsToMatchersMap = new Map< string, @@ -35,7 +34,7 @@ const picomatchOptions = {dot: true}; * isMatch('pizza.js'); // true * isMatch('pizza.test.js'); // false */ -export default function globsToMatcher(globs: Array): Matcher { +export default function globsToMatcher(globs: Array): Matcher { if (globs.length === 0) { // Since there were no globs given, we can simply have a fast path here and // return with a very simple function. diff --git a/packages/jest-util/src/replacePathSepForGlob.ts b/packages/jest-util/src/replacePathSepForGlob.ts index a21af255e483..7ec8a1d97b14 100644 --- a/packages/jest-util/src/replacePathSepForGlob.ts +++ b/packages/jest-util/src/replacePathSepForGlob.ts @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -import type {Config} from '@jest/types'; - -export default function replacePathSepForGlob(path: Config.Path): Config.Glob { +export default function replacePathSepForGlob(path: string): string { return path.replace(/\\(?![{}()+?.^$])/g, '/'); } diff --git a/packages/jest-util/src/requireOrImportModule.ts b/packages/jest-util/src/requireOrImportModule.ts index e060e983154c..13311cc84b4e 100644 --- a/packages/jest-util/src/requireOrImportModule.ts +++ b/packages/jest-util/src/requireOrImportModule.ts @@ -7,11 +7,10 @@ import {isAbsolute} from 'path'; import {pathToFileURL} from 'url'; -import type {Config} from '@jest/types'; import interopRequireDefault from './interopRequireDefault'; export default async function requireOrImportModule( - filePath: Config.Path, + filePath: string, applyInteropRequireDefault = true, ): Promise { if (!isAbsolute(filePath) && filePath[0] === '.') { diff --git a/packages/jest-util/src/tryRealpath.ts b/packages/jest-util/src/tryRealpath.ts index 4d3377ca3241..0674c5e4cdf8 100644 --- a/packages/jest-util/src/tryRealpath.ts +++ b/packages/jest-util/src/tryRealpath.ts @@ -6,9 +6,8 @@ */ import {realpathSync} from 'graceful-fs'; -import type {Config} from '@jest/types'; -export default function tryRealpath(path: Config.Path): Config.Path { +export default function tryRealpath(path: string): string { try { path = realpathSync.native(path); } catch (error: any) { diff --git a/packages/jest-watcher/src/types.ts b/packages/jest-watcher/src/types.ts index 12b196dcd066..63e6f2b81bd0 100644 --- a/packages/jest-watcher/src/types.ts +++ b/packages/jest-watcher/src/types.ts @@ -17,7 +17,7 @@ type TestSuiteInfo = { export type JestHookExposedFS = { projects: Array<{ config: Config.ProjectConfig; - testPaths: Array; + testPaths: Array; }>; }; diff --git a/yarn.lock b/yarn.lock index d72e8c0a8e57..f2a4eab9107f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6550,7 +6550,6 @@ __metadata: "@babel/core": ^7.8.0 "@jest/test-utils": ^28.0.0-alpha.1 "@jest/transform": ^28.0.0-alpha.1 - "@jest/types": ^28.0.0-alpha.1 "@types/babel__core": ^7.1.14 "@types/graceful-fs": ^4.1.3 babel-plugin-istanbul: ^6.1.1 @@ -10131,7 +10130,6 @@ __metadata: dependencies: "@jest/expect-utils": ^28.0.0-alpha.1 "@jest/test-utils": ^28.0.0-alpha.1 - "@jest/types": ^28.0.0-alpha.1 "@tsd/typescript": ~4.5.5 chalk: ^4.0.0 fast-check: ^2.0.0 @@ -12841,7 +12839,6 @@ __metadata: version: 0.0.0-use.local resolution: "jest-changed-files@workspace:packages/jest-changed-files" dependencies: - "@jest/types": ^28.0.0-alpha.1 execa: ^5.0.0 throat: ^6.0.1 languageName: unknown @@ -13280,7 +13277,6 @@ __metadata: version: 0.0.0-use.local resolution: "jest-resolve@workspace:packages/jest-resolve" dependencies: - "@jest/types": ^28.0.0-alpha.1 "@types/graceful-fs": ^4.1.3 "@types/resolve": ^1.20.0 chalk: ^4.0.0