diff --git a/.eslintrc.js b/.eslintrc.js index 347ca90d1ae8..54158179d1d1 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -20,6 +20,7 @@ module.exports = { parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint/eslint-plugin'], rules: { + '@typescript-eslint/array-type': ['error', 'array'], '@typescript-eslint/no-unused-vars': [ 'error', {argsIgnorePattern: '^_'}, diff --git a/packages/babel-plugin-jest-hoist/src/index.ts b/packages/babel-plugin-jest-hoist/src/index.ts index f99fa9675691..add52efbe48c 100644 --- a/packages/babel-plugin-jest-hoist/src/index.ts +++ b/packages/babel-plugin-jest-hoist/src/index.ts @@ -89,10 +89,10 @@ const IDVisitor = { }; const FUNCTIONS: { - [key: string]: (args: Array) => boolean; + [key: string]: (args: NodePath[]) => boolean; } = Object.create(null); -FUNCTIONS.mock = (args: Array) => { +FUNCTIONS.mock = (args: NodePath[]) => { if (args.length === 1) { return args[0].isStringLiteral() || args[0].isLiteral(); } else if (args.length === 2 || args.length === 3) { @@ -146,13 +146,12 @@ FUNCTIONS.mock = (args: Array) => { return false; }; -FUNCTIONS.unmock = (args: Array) => +FUNCTIONS.unmock = (args: NodePath[]) => args.length === 1 && args[0].isStringLiteral(); -FUNCTIONS.deepUnmock = (args: Array) => +FUNCTIONS.deepUnmock = (args: NodePath[]) => args.length === 1 && args[0].isStringLiteral(); -FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = ( - args: Array, -) => args.length === 0; +FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = (args: NodePath[]) => + args.length === 0; export = () => { const shouldHoistExpression = (expr: NodePath): boolean => { diff --git a/packages/diff-sequences/src/__tests__/index.test.ts b/packages/diff-sequences/src/__tests__/index.test.ts index 6652c756b7fb..89a9a9fa994e 100644 --- a/packages/diff-sequences/src/__tests__/index.test.ts +++ b/packages/diff-sequences/src/__tests__/index.test.ts @@ -61,7 +61,7 @@ describe('invalid arg', () => { }); // Return length of longest common subsequence according to Object.is method. -const countCommonObjectIs = (a: Array, b: Array): number => { +const countCommonObjectIs = (a: any[], b: any[]): number => { let n = 0; diff( a.length, @@ -75,7 +75,7 @@ const countCommonObjectIs = (a: Array, b: Array): number => { }; // Return length of longest common subsequence according to === operator. -const countCommonStrictEquality = (a: Array, b: Array): number => { +const countCommonStrictEquality = (a: any[], b: any[]): number => { let n = 0; diff( a.length, @@ -133,8 +133,8 @@ const assertEnd = (name: string, val: number, end: number) => { }; const assertCommonItems = ( - a: Array | string, - b: Array | string, + a: any[] | string, + b: any[] | string, nCommon: number, aCommon: number, bCommon: number, @@ -191,10 +191,7 @@ const countDifferences = ( }; // Return array of items in a longest common subsequence of array-like objects. -const findCommonItems = ( - a: Array | string, - b: Array | string, -): Array => { +const findCommonItems = (a: any[] | string, b: any[] | string): any[] => { const aLength = a.length; const bLength = b.length; const isCommon = (aIndex: number, bIndex: number) => { @@ -231,9 +228,9 @@ const findCommonItems = ( // Assert that array-like objects have the expected common items. const expectCommonItems = ( - a: Array | string, - b: Array | string, - expected: Array, + a: any[] | string, + b: any[] | string, + expected: any[], ) => { expect(findCommonItems(a, b)).toEqual(expected); @@ -730,7 +727,7 @@ const assertCommonSubstring = ( }; // Return array of substrings in a longest common subsequence of strings. -const findCommonSubstrings = (a: string, b: string): Array => { +const findCommonSubstrings = (a: string, b: string): string[] => { const array = []; diff( a.length, diff --git a/packages/diff-sequences/src/index.ts b/packages/diff-sequences/src/index.ts index 5dbbc4c6bd65..e73806c39b9a 100644 --- a/packages/diff-sequences/src/index.ts +++ b/packages/diff-sequences/src/index.ts @@ -76,7 +76,7 @@ export type Callbacks = { // and also updates the index arrays in place to cut memory in half. // kF = 2 * iF - d // kR = d - 2 * iR -type Indexes = Array; +type Indexes = number[]; // Division of index intervals in sequences a and b at the middle change. // Invariant: intervals do not have common items at the start or end. @@ -657,7 +657,7 @@ const findSubsequences = ( bStart: number, bEnd: number, transposed: boolean, - callbacks: Array, + callbacks: Callbacks[], aIndexesF: Indexes, // temporary memory, not input nor output aIndexesR: Indexes, // temporary memory, not input nor output division: Division, // temporary memory, not input nor output diff --git a/packages/expect/src/asymmetricMatchers.ts b/packages/expect/src/asymmetricMatchers.ts index 1742cf7711ae..f9d1cfbfba2b 100644 --- a/packages/expect/src/asymmetricMatchers.ts +++ b/packages/expect/src/asymmetricMatchers.ts @@ -105,13 +105,13 @@ class Anything extends AsymmetricMatcher { } } -class ArrayContaining extends AsymmetricMatcher> { - constructor(sample: Array, inverse: boolean = false) { +class ArrayContaining extends AsymmetricMatcher { + constructor(sample: unknown[], inverse: boolean = false) { super(sample); this.inverse = inverse; } - asymmetricMatch(other: Array) { + asymmetricMatch(other: unknown[]) { if (!Array.isArray(this.sample)) { throw new Error( `You must provide an array to ${this.toString()}, not '` + @@ -241,9 +241,9 @@ class StringMatching extends AsymmetricMatcher { export const any = (expectedObject: any) => new Any(expectedObject); export const anything = () => new Anything(); -export const arrayContaining = (sample: Array) => +export const arrayContaining = (sample: unknown[]) => new ArrayContaining(sample); -export const arrayNotContaining = (sample: Array) => +export const arrayNotContaining = (sample: unknown[]) => new ArrayContaining(sample, true); export const objectContaining = (sample: Object) => new ObjectContaining(sample); diff --git a/packages/expect/src/index.ts b/packages/expect/src/index.ts index 500b2f19945c..f4f2002897e9 100644 --- a/packages/expect/src/index.ts +++ b/packages/expect/src/index.ts @@ -82,7 +82,7 @@ const getPromiseMatcher = (name: string, matcher: any) => { return null; }; -const expect: any = (actual: any, ...rest: Array): ExpectationObject => { +const expect: any = (actual: any, ...rest: any[]): ExpectationObject => { if (rest.length !== 0) { throw new Error('Expect takes at most one argument.'); } @@ -384,7 +384,7 @@ function assertions(expected: number) { getState().expectedAssertionsNumber = expected; getState().expectedAssertionsNumberError = error; } -function hasAssertions(...args: Array) { +function hasAssertions(...args: any[]) { const error = new Error(); if (Error.captureStackTrace) { Error.captureStackTrace(error, hasAssertions); diff --git a/packages/expect/src/matchers.ts b/packages/expect/src/matchers.ts index e76bd64c63c6..8838627f9cda 100644 --- a/packages/expect/src/matchers.ts +++ b/packages/expect/src/matchers.ts @@ -38,7 +38,7 @@ import { import {equals} from './jasmineUtils'; type ContainIterable = - | Array + | unknown[] | Set | NodeListOf | DOMTokenList @@ -565,7 +565,7 @@ const matchers: MatchersObject = { toHaveProperty( this: MatcherState, object: object, - keyPath: string | Array, + keyPath: string | string[], value?: unknown, ) { const valuePassed = arguments.length === 3; diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 60e5606d6a6a..6bb719dacd50 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -172,7 +172,7 @@ const createToReturnTimesMatcher = (matcherName: string) => ( const createToBeCalledWithMatcher = (matcherName: string) => ( received: any, - ...expected: Array + ...expected: unknown[] ): SyncExpectationResult => { ensureMock(received, matcherName); @@ -253,7 +253,7 @@ const createToReturnWithMatcher = (matcherName: string) => ( const createLastCalledWithMatcher = (matcherName: string) => ( received: any, - ...expected: Array + ...expected: unknown[] ): SyncExpectationResult => { ensureMock(received, matcherName); @@ -332,7 +332,7 @@ const createLastReturnedMatcher = (matcherName: string) => ( const createNthCalledWithMatcher = (matcherName: string) => ( received: any, nth: number, - ...expected: Array + ...expected: unknown[] ): SyncExpectationResult => { ensureMock(received, matcherName); @@ -517,11 +517,7 @@ const getPrintedReturnValues = (calls: any[], limit: number): string => { return result.join('\n\n '); }; -const formatReceivedCalls = ( - calls: Array, - limit: number, - options: any, -) => { +const formatReceivedCalls = (calls: any[], limit: number, options: any) => { if (calls.length) { const but = options && options.sameSentence ? 'but' : 'But'; const count = calls.length - limit; @@ -540,7 +536,7 @@ const formatReceivedCalls = ( }; const formatMismatchedCalls = ( - calls: Array, + calls: any[], expected: any, limit: number, ): string => { @@ -560,7 +556,7 @@ const formatMismatchedCalls = ( }; const formatMismatchedReturnValues = ( - returnValues: Array, + returnValues: any[], expected: any, limit: number, ): string => { diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 106abcb03995..2116ea4697bc 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -36,7 +36,7 @@ export type MatcherState = { equals: ( a: unknown, b: unknown, - customTesters?: Array, + customTesters?: Tester[], strictCheck?: boolean, ) => boolean; expand?: boolean; @@ -44,7 +44,7 @@ export type MatcherState = { isExpectingAssertions?: boolean; isNot: boolean; promise: string; - suppressedErrors: Array; + suppressedErrors: Error[]; testPath?: Config.Path; utils: typeof jestMatcherUtils & { iterableEquality: Tester; @@ -59,18 +59,18 @@ export type Expect = { addSnapshotSerializer(arg0: any): void; assertions(arg0: number): void; extend(arg0: any): void; - extractExpectedAssertionsErrors: () => Array<{ + extractExpectedAssertionsErrors: () => { actual: string | number; error: Error; expected: string; - }>; + }[]; getState(): MatcherState; hasAssertions(): void; setState(arg0: any): void; any(expectedObject: any): AsymmetricMatcher; anything(): AsymmetricMatcher; - arrayContaining(sample: Array): AsymmetricMatcher; + arrayContaining(sample: any[]): AsymmetricMatcher; objectContaining(sample: Object): AsymmetricMatcher; stringContaining(expected: string): AsymmetricMatcher; stringMatching(expected: string | RegExp): AsymmetricMatcher; diff --git a/packages/expect/src/utils.ts b/packages/expect/src/utils.ts index 23d1fe1af797..599c27f26c9f 100644 --- a/packages/expect/src/utils.ts +++ b/packages/expect/src/utils.ts @@ -16,7 +16,7 @@ import { type GetPath = { hasEndProp?: boolean; lastTraversedObject: unknown; - traversedPath: Array; + traversedPath: string[]; value?: unknown; }; @@ -49,7 +49,7 @@ export const hasOwnProperty = (object: object, key: string) => export const getPath = ( object: object, - propertyPath: string | Array, + propertyPath: string | string[], ): GetPath => { if (!Array.isArray(propertyPath)) { propertyPath = (propertyPath as string).split('.'); @@ -262,10 +262,10 @@ export const sparseArrayEquality = (a: unknown, b: unknown) => { }; export const partition = ( - items: Array, + items: T[], predicate: (arg: T) => boolean, -): [Array, Array] => { - const result: [Array, Array] = [[], []]; +): [T[], T[]] => { + const result: [T[], T[]] = [[], []]; items.forEach(item => result[predicate(item) ? 0 : 1].push(item)); diff --git a/packages/jest-changed-files/src/git.ts b/packages/jest-changed-files/src/git.ts index ed0d4a9b90a1..96d8017f88cd 100644 --- a/packages/jest-changed-files/src/git.ts +++ b/packages/jest-changed-files/src/git.ts @@ -13,9 +13,9 @@ import {Config} from '@jest/types'; import {SCMAdapter} from './types'; const findChangedFilesUsingCommand = async ( - args: Array, + args: string[], cwd: Config.Path, -): Promise> => { +): Promise => { const result = await execa('git', args, {cwd}); return result.stdout @@ -29,8 +29,7 @@ const adapter: SCMAdapter = { const changedSince: string | undefined = options && (options.withAncestor ? 'HEAD^' : options.changedSince); - const includePaths: Array = - (options && options.includePaths) || []; + const includePaths: Config.Path[] = (options && options.includePaths) || []; if (options && options.lastCommit) { return findChangedFilesUsingCommand( diff --git a/packages/jest-changed-files/src/hg.ts b/packages/jest-changed-files/src/hg.ts index 89d4aea508b2..6956db91d00f 100644 --- a/packages/jest-changed-files/src/hg.ts +++ b/packages/jest-changed-files/src/hg.ts @@ -16,8 +16,7 @@ const env = {...process.env, HGPLAIN: '1'}; const adapter: SCMAdapter = { findChangedFiles: async (cwd, options) => { - const includePaths: Array = - (options && options.includePaths) || []; + const includePaths: Config.Path[] = (options && options.includePaths) || []; const args = ['status', '-amnu']; if (options && options.withAncestor) { diff --git a/packages/jest-changed-files/src/types.ts b/packages/jest-changed-files/src/types.ts index 3d040a6c49dd..1816a4e6005f 100644 --- a/packages/jest-changed-files/src/types.ts +++ b/packages/jest-changed-files/src/types.ts @@ -11,7 +11,7 @@ export type Options = { lastCommit?: boolean; withAncestor?: boolean; changedSince?: string; - includePaths?: Array; + includePaths?: Config.Path[]; }; type ChangedFiles = Set; @@ -25,6 +25,6 @@ export type SCMAdapter = { findChangedFiles: ( cwd: Config.Path, options: Options, - ) => Promise>; + ) => Promise; getRoot: (cwd: Config.Path) => Promise; }; diff --git a/packages/jest-circus/src/index.ts b/packages/jest-circus/src/index.ts index d4ed333084b7..2d6aa631a7de 100644 --- a/packages/jest-circus/src/index.ts +++ b/packages/jest-circus/src/index.ts @@ -103,7 +103,7 @@ const test: Global.It = (() => { const only = (testName: TestName, fn: TestFn, timeout?: number): void => _addTest(testName, 'only', fn, test.only, timeout); - test.todo = (testName: TestName, ...rest: Array): void => { + test.todo = (testName: TestName, ...rest: any[]): void => { if (rest.length > 0 || typeof testName !== 'string') { throw new ErrorWithStack( 'Todo must be called with only a description.', 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 577a5e94431c..fa0aefe438dd 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts @@ -135,43 +135,43 @@ export const runAndTransformResultsToJestFormat = async ({ let numPendingTests = 0; let numTodoTests = 0; - const assertionResults: Array< - TestResult.AssertionResult - > = runResult.testResults.map(testResult => { - let status: TestResult.Status; - if (testResult.status === 'skip') { - status = 'pending'; - numPendingTests += 1; - } else if (testResult.status === 'todo') { - status = 'todo'; - numTodoTests += 1; - } else if (testResult.errors.length) { - status = 'failed'; - numFailingTests += 1; - } else { - status = 'passed'; - numPassingTests += 1; - } + const assertionResults: TestResult.AssertionResult[] = runResult.testResults.map( + testResult => { + let status: TestResult.Status; + if (testResult.status === 'skip') { + status = 'pending'; + numPendingTests += 1; + } else if (testResult.status === 'todo') { + status = 'todo'; + numTodoTests += 1; + } else if (testResult.errors.length) { + status = 'failed'; + numFailingTests += 1; + } else { + status = 'passed'; + numPassingTests += 1; + } - const ancestorTitles = testResult.testPath.filter( - name => name !== ROOT_DESCRIBE_BLOCK_NAME, - ); - const title = ancestorTitles.pop(); + const ancestorTitles = testResult.testPath.filter( + name => name !== ROOT_DESCRIBE_BLOCK_NAME, + ); + const title = ancestorTitles.pop(); - return { - ancestorTitles, - duration: testResult.duration, - failureMessages: testResult.errors, - fullName: title - ? ancestorTitles.concat(title).join(' ') - : ancestorTitles.join(' '), - invocations: testResult.invocations, - location: testResult.location, - numPassingAsserts: 0, - status, - title: testResult.testPath[testResult.testPath.length - 1], - }; - }); + return { + ancestorTitles, + duration: testResult.duration, + failureMessages: testResult.errors, + fullName: title + ? ancestorTitles.concat(title).join(' ') + : ancestorTitles.join(' '), + invocations: testResult.invocations, + location: testResult.location, + numPassingAsserts: 0, + status, + title: testResult.testPath[testResult.testPath.length - 1], + }; + }, + ); let failureMessage = formatResultsErrors( assertionResults, diff --git a/packages/jest-circus/src/state.ts b/packages/jest-circus/src/state.ts index 8f684d254d16..52b475224670 100644 --- a/packages/jest-circus/src/state.ts +++ b/packages/jest-circus/src/state.ts @@ -11,10 +11,7 @@ import {makeDescribe} from './utils'; import eventHandler from './eventHandler'; import formatNodeAssertErrors from './formatNodeAssertErrors'; -const eventHandlers: Array = [ - eventHandler, - formatNodeAssertErrors, -]; +const eventHandlers: EventHandler[] = [eventHandler, formatNodeAssertErrors]; export const ROOT_DESCRIBE_BLOCK_NAME = 'ROOT_DESCRIBE_BLOCK'; diff --git a/packages/jest-circus/src/types.ts b/packages/jest-circus/src/types.ts index bdc9cc8f2d1c..4dc052ce69b5 100644 --- a/packages/jest-circus/src/types.ts +++ b/packages/jest-circus/src/types.ts @@ -157,25 +157,23 @@ export type Event = export type TestStatus = 'skip' | 'done' | 'todo'; export type TestResult = { duration: number | null | undefined; - errors: Array; + errors: FormattedError[]; invocations: number; status: TestStatus; location: {column: number; line: number} | null | undefined; - testPath: Array; + testPath: (TestName | BlockName)[]; }; export type RunResult = { - unhandledErrors: Array; + unhandledErrors: FormattedError[]; testResults: TestResults; }; -export type TestResults = Array; +export type TestResults = TestResult[]; export type GlobalErrorHandlers = { - uncaughtException: Array<(exception: Exception) => void>; - unhandledRejection: Array< - (exception: Exception, promise: Promise) => void - >; + uncaughtException: ((exception: Exception) => void)[]; + unhandledRejection: ((exception: Exception, promise: Promise) => void)[]; }; export type State = { @@ -191,20 +189,20 @@ export type State = { rootDescribeBlock: DescribeBlock; testNamePattern: RegExp | undefined | null; testTimeout: number; - unhandledErrors: Array; + unhandledErrors: Exception[]; includeTestLocationInResult: boolean; }; export type DescribeBlock = { - children: Array; - hooks: Array; + children: DescribeBlock[]; + hooks: Hook[]; mode: BlockMode; name: BlockName; parent: DescribeBlock | undefined | null; - tests: Array; + tests: TestEntry[]; }; -export type TestError = Exception | Array<[Exception | undefined, Exception]>; // the error from the test, as well as a backup error for async +export type TestError = Exception | [Exception | undefined, Exception][]; // the error from the test, as well as a backup error for async export type TestEntry = { asyncError: Exception; // Used if the test failure contains no usable stack trace diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts index 7917d1356e9d..08559bc251e8 100644 --- a/packages/jest-circus/src/utils.ts +++ b/packages/jest-circus/src/utils.ts @@ -92,8 +92,8 @@ const hasEnabledTest = (describeBlock: DescribeBlock): boolean => { export const getAllHooksForDescribe = (describe: DescribeBlock) => { const result: { - beforeAll: Array; - afterAll: Array; + beforeAll: Hook[]; + afterAll: Hook[]; } = { afterAll: [], beforeAll: [], @@ -117,8 +117,8 @@ export const getAllHooksForDescribe = (describe: DescribeBlock) => { export const getEachHooksForTest = (test: TestEntry) => { const result: { - beforeEach: Array; - afterEach: Array; + beforeEach: Hook[]; + afterEach: Hook[]; } = {afterEach: [], beforeEach: []}; let block: DescribeBlock | undefined | null = test.parent; @@ -240,7 +240,7 @@ export const getTestDuration = (test: TestEntry): number | null => { export const makeRunResult = ( describeBlock: DescribeBlock, - unhandledErrors: Array, + unhandledErrors: Error[], ): RunResult => ({ testResults: makeTestResults(describeBlock), unhandledErrors: unhandledErrors.map(_formatError), diff --git a/packages/jest-diff/src/diffStrings.ts b/packages/jest-diff/src/diffStrings.ts index b71259c40485..32f2df93d0fd 100644 --- a/packages/jest-diff/src/diffStrings.ts +++ b/packages/jest-diff/src/diffStrings.ts @@ -55,8 +55,8 @@ type Put = (line: string) => void; const formatDelete = ( aStart: number, aEnd: number, - aLinesUn: Array, - aLinesIn: Array, + aLinesUn: string[], + aLinesIn: string[], put: Put, ) => { const highlightSpaces = getHighlightSpaces(aLinesUn !== aLinesIn); @@ -73,8 +73,8 @@ const formatDelete = ( const formatInsert = ( bStart: number, bEnd: number, - bLinesUn: Array, - bLinesIn: Array, + bLinesUn: string[], + bLinesIn: string[], put: Put, ) => { const highlightSpaces = getHighlightSpaces(bLinesUn !== bLinesIn); @@ -94,9 +94,9 @@ const formatCommon = ( aCommon: number, bCommon: number, // aLinesUn has lines that are equal to bLinesUn within a common subsequence - aLinesIn: Array, - bLinesUn: Array, - bLinesIn: Array, + aLinesIn: string[], + bLinesUn: string[], + bLinesIn: string[], put: Put, ) => { const highlightSpaces = getHighlightSpaces(bLinesUn !== bLinesIn); @@ -120,10 +120,10 @@ const formatCommon = ( // jest --expand // Return formatted diff as joined string of all lines. const diffExpand = ( - aLinesUn: Array, - bLinesUn: Array, - aLinesIn: Array, - bLinesIn: Array, + aLinesUn: string[], + bLinesUn: string[], + aLinesIn: string[], + bLinesIn: string[], ): string => { const isCommon: Callbacks['isCommon'] = (aIndex, bIndex) => aLinesUn[aIndex] === bLinesUn[bIndex]; @@ -183,10 +183,10 @@ const getContextLines = (options?: DiffOptions): number => // but if some common lines are omitted because there are more than the context, // then a “patch mark” precedes each set of adjacent changed and common lines. const diffNoExpand = ( - aLinesUn: Array, - bLinesUn: Array, - aLinesIn: Array, - bLinesIn: Array, + aLinesUn: string[], + bLinesUn: string[], + aLinesIn: string[], + bLinesIn: string[], nContextLines: number, ): string => { const isCommon: Callbacks['isCommon'] = (aIndex, bIndex) => diff --git a/packages/jest-haste-map/src/HasteFS.ts b/packages/jest-haste-map/src/HasteFS.ts index de3628871f27..c13d0c4718d2 100644 --- a/packages/jest-haste-map/src/HasteFS.ts +++ b/packages/jest-haste-map/src/HasteFS.ts @@ -31,7 +31,7 @@ export default class HasteFS { return (fileMetadata && fileMetadata[H.SIZE]) || null; } - getDependencies(file: Config.Path): Array | null { + getDependencies(file: Config.Path): string[] | null { const fileMetadata = this._getFileData(file); return (fileMetadata && fileMetadata[H.DEPENDENCIES]) || null; } @@ -45,7 +45,7 @@ export default class HasteFS { return this._getFileData(file) != null; } - getAllFiles(): Array { + getAllFiles(): Config.Path[] { return Array.from(this.getAbsoluteFileIterator()); } @@ -59,7 +59,7 @@ export default class HasteFS { } } - matchFiles(pattern: RegExp | string): Array { + matchFiles(pattern: RegExp | string): Config.Path[] { if (!(pattern instanceof RegExp)) { pattern = new RegExp(pattern); } @@ -73,7 +73,7 @@ export default class HasteFS { } matchFilesWithGlob( - globs: Array, + globs: Config.Glob[], root: Config.Path | null, ): Set { const files = new Set(); diff --git a/packages/jest-haste-map/src/crawlers/node.ts b/packages/jest-haste-map/src/crawlers/node.ts index 6813e79ac519..7a49a3f1d215 100644 --- a/packages/jest-haste-map/src/crawlers/node.ts +++ b/packages/jest-haste-map/src/crawlers/node.ts @@ -12,13 +12,13 @@ import H from '../constants'; import * as fastPath from '../lib/fast_path'; import {IgnoreMatcher, InternalHasteMap, CrawlerOptions} from '../types'; -type Result = Array<[/* id */ string, /* mtime */ number, /* size */ number]>; +type Result = [/* id */ string, /* mtime */ number, /* size */ number][]; type Callback = (result: Result) => void; function find( - roots: Array, - extensions: Array, + roots: string[], + extensions: string[], ignore: IgnoreMatcher, callback: Callback, ): void { @@ -73,8 +73,8 @@ function find( } function findNative( - roots: Array, - extensions: Array, + roots: string[], + extensions: string[], ignore: IgnoreMatcher, callback: Callback, ): void { diff --git a/packages/jest-haste-map/src/crawlers/watchman.ts b/packages/jest-haste-map/src/crawlers/watchman.ts index b7f5fc453f0b..8f0cc75ed7cd 100644 --- a/packages/jest-haste-map/src/crawlers/watchman.ts +++ b/packages/jest-haste-map/src/crawlers/watchman.ts @@ -13,7 +13,7 @@ import normalizePathSep from '../lib/normalizePathSep'; import H from '../constants'; import {InternalHasteMap, CrawlerOptions, FileMetaData} from '../types'; -type WatchmanRoots = Map>; +type WatchmanRoots = Map; const watchmanURL = 'https://facebook.github.io/watchman/docs/troubleshooting.html'; @@ -42,7 +42,7 @@ export = async function watchmanCrawl( client.on('error', error => (clientError = WatchmanError(error))); // TODO: type better than `any` - const cmd = (...args: Array): Promise => + const cmd = (...args: any[]): Promise => new Promise((resolve, reject) => client.command(args, (error, result) => error ? reject(WatchmanError(error)) : resolve(result), @@ -58,7 +58,7 @@ export = async function watchmanCrawl( } async function getWatchmanRoots( - roots: Array, + roots: Config.Path[], ): 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 fedc0f81a019..c98058cdfd62 100644 --- a/packages/jest-haste-map/src/index.ts +++ b/packages/jest-haste-map/src/index.ts @@ -50,7 +50,7 @@ type Options = { computeSha1?: boolean; console?: Console; dependencyExtractor?: string; - extensions: Array; + extensions: string[]; forceNodeFilesystemAPI?: boolean; hasteImplModulePath?: string; ignorePattern?: HasteRegExp; @@ -58,12 +58,12 @@ type Options = { maxWorkers: number; mocksPattern?: string; name: string; - platforms: Array; - providesModuleNodeModules?: Array; + platforms: string[]; + providesModuleNodeModules?: string[]; resetCache?: boolean; retainAllFiles: boolean; rootDir: string; - roots: Array; + roots: string[]; throwOnModuleCollision?: boolean; useWatchman?: boolean; watch?: boolean; @@ -74,7 +74,7 @@ type InternalOptions = { computeDependencies: boolean; computeSha1: boolean; dependencyExtractor?: string; - extensions: Array; + extensions: string[]; forceNodeFilesystemAPI: boolean; hasteImplModulePath?: string; ignorePattern?: HasteRegExp; @@ -82,11 +82,11 @@ type InternalOptions = { maxWorkers: number; mocksPattern: RegExp | null; name: string; - platforms: Array; + platforms: string[]; resetCache?: boolean; retainAllFiles: boolean; rootDir: string; - roots: Array; + roots: string[]; throwOnModuleCollision: boolean; useWatchman: boolean; watch: boolean; @@ -124,7 +124,7 @@ const canUseWatchman = ((): boolean => { const escapePathSeparator = (string: string) => path.sep === '\\' ? string.replace(/(\/|\\)/g, '\\\\') : string; -const getWhiteList = (list: Array | undefined): RegExp | null => { +const getWhiteList = (list: string[] | undefined): RegExp | null => { if (list && list.length) { const newList = list.map(item => escapePathSeparator(item.replace(/(\/)/g, path.sep)), @@ -228,7 +228,7 @@ class HasteMap extends EventEmitter { private _changeInterval?: NodeJS.Timeout; private _console: Console; private _options: InternalOptions; - private _watchers: Array; + private _watchers: Watcher[]; private _whitelist: RegExp | null; private _worker: WorkerInterface | null; @@ -314,7 +314,7 @@ class HasteMap extends EventEmitter { static getCacheFilePath( tmpdir: Config.Path, name: string, - ...extra: Array + ...extra: string[] ): string { const hash = crypto.createHash('md5').update(extra.join('')); return path.join( @@ -386,7 +386,7 @@ class HasteMap extends EventEmitter { * 2. crawl the file system. */ private _buildFileMap(): Promise<{ - deprecatedFiles: Array<{moduleName: string; path: string}>; + deprecatedFiles: {moduleName: string; path: string}[]; hasteMap: InternalHasteMap; }> { const read = this._options.resetCache ? this._createEmptyMap : this.read; @@ -395,7 +395,7 @@ class HasteMap extends EventEmitter { .then(() => read.call(this)) .catch(() => this._createEmptyMap()) .then(cachedHasteMap => { - const cachedFiles: Array<{moduleName: string; path: string}> = []; + const cachedFiles: {moduleName: string; path: string}[] = []; for (const [relativeFilePath, fileMetadata] of cachedHasteMap.files) { const moduleName = fileMetadata[H.ID]; cachedFiles.push({moduleName, path: relativeFilePath}); @@ -609,7 +609,7 @@ class HasteMap extends EventEmitter { } private _buildHasteMap(data: { - deprecatedFiles: Array<{moduleName: string; path: string}>; + deprecatedFiles: {moduleName: string; path: string}[]; hasteMap: InternalHasteMap; }): Promise { const {deprecatedFiles, hasteMap} = data; @@ -763,11 +763,11 @@ class HasteMap extends EventEmitter { const rootDir = this._options.rootDir; let changeQueue: Promise = Promise.resolve(); - let eventsQueue: Array<{ + let eventsQueue: { filePath: Config.Path; stat: fs.Stats | undefined; type: string; - }> = []; + }[] = []; // We only need to copy the entire haste map once on every "frame". let mustCopy = true; diff --git a/packages/jest-haste-map/src/lib/dependencyExtractor.ts b/packages/jest-haste-map/src/lib/dependencyExtractor.ts index 1e10b59db7c2..4ec830eabcca 100644 --- a/packages/jest-haste-map/src/lib/dependencyExtractor.ts +++ b/packages/jest-haste-map/src/lib/dependencyExtractor.ts @@ -19,15 +19,15 @@ const RIGHT_PARENTHESIS = '\\)'; const WHITESPACE = '\\s*'; const OPTIONAL_COMMA = '(:?,\\s*)?'; -function createRegExp(parts: Array, flags: string) { +function createRegExp(parts: string[], flags: string) { return new RegExp(parts.join(''), flags); } -function alternatives(...parts: Array) { +function alternatives(...parts: string[]) { return `(?:${parts.join('|')})`; } -function functionCallStart(...names: Array) { +function functionCallStart(...names: string[]) { return [ NOT_A_DOT, WORD_SEPARATOR, diff --git a/packages/jest-haste-map/src/lib/getPlatformExtension.ts b/packages/jest-haste-map/src/lib/getPlatformExtension.ts index f9dac1dace0d..7682ed255b15 100644 --- a/packages/jest-haste-map/src/lib/getPlatformExtension.ts +++ b/packages/jest-haste-map/src/lib/getPlatformExtension.ts @@ -10,7 +10,7 @@ const SUPPORTED_PLATFORM_EXTS = new Set(['android', 'ios', 'native', 'web']); // Extract platform extension: index.ios.js -> ios export default function getPlatformExtension( file: string, - platforms?: Array, + platforms?: string[], ): string | null { const last = file.lastIndexOf('.'); const secondToLast = file.lastIndexOf('.', last - 1); diff --git a/packages/jest-haste-map/src/types.ts b/packages/jest-haste-map/src/types.ts index c5e85fc8d9b9..028cbb6ff247 100644 --- a/packages/jest-haste-map/src/types.ts +++ b/packages/jest-haste-map/src/types.ts @@ -10,7 +10,7 @@ import ModuleMap from './ModuleMap'; import HasteFS from './HasteFS'; export type IgnoreMatcher = (item: string) => boolean; -export type Mapper = (item: string) => Array | null; +export type Mapper = (item: string) => string[] | null; export type WorkerMessage = { computeDependencies: boolean; @@ -22,7 +22,7 @@ export type WorkerMessage = { }; export type WorkerMetadata = { - dependencies: Array | undefined | null; + dependencies: string[] | undefined | null; id: string | undefined | null; module: ModuleMetaData | undefined | null; sha1: string | undefined | null; @@ -31,12 +31,12 @@ export type WorkerMetadata = { export type CrawlerOptions = { computeSha1: boolean; data: InternalHasteMap; - extensions: Array; + extensions: string[]; forceNodeFilesystemAPI: boolean; ignore: IgnoreMatcher; mapper?: Mapper | null; rootDir: string; - roots: Array; + roots: string[]; }; export type HasteImpl = { @@ -50,7 +50,7 @@ export type FileMetaData = [ /* mtime */ number, /* size */ number, /* visited */ 0 | 1, - /* dependencies */ Array, + /* dependencies */ string[], /* sha1 */ string | null | undefined ]; diff --git a/packages/jest-matcher-utils/src/index.ts b/packages/jest-matcher-utils/src/index.ts index 6207960d5af7..abe60b349843 100644 --- a/packages/jest-matcher-utils/src/index.ts +++ b/packages/jest-matcher-utils/src/index.ts @@ -223,7 +223,7 @@ export const pluralize = (word: string, count: number) => type PrintLabel = (string: string) => string; -export const getLabelPrinter = (...strings: Array): PrintLabel => { +export const getLabelPrinter = (...strings: string[]): PrintLabel => { const maxLength = strings.reduce( (max, string) => (string.length > max ? string.length : max), 0, diff --git a/packages/jest-message-util/src/index.ts b/packages/jest-message-util/src/index.ts index f1c6ad699215..507c912f3f3d 100644 --- a/packages/jest-message-util/src/index.ts +++ b/packages/jest-message-util/src/index.ts @@ -287,15 +287,15 @@ export const formatStackTrace = ( }; export const formatResultsErrors = ( - testResults: Array, + testResults: AssertionResult[], config: StackTraceConfig, options: StackTraceOptions, testPath?: Path, ): string | null => { - type FailedResults = Array<{ + type FailedResults = { content: string; result: AssertionResult; - }>; + }[]; const failedResults: FailedResults = testResults.reduce( (errors, result) => { diff --git a/packages/jest-mock/src/index.ts b/packages/jest-mock/src/index.ts index a23a49d2fe36..604d3fefbb19 100644 --- a/packages/jest-mock/src/index.ts +++ b/packages/jest-mock/src/index.ts @@ -61,13 +61,13 @@ type MockFunctionResult = { }; type MockFunctionState = { - calls: Array; - instances: Array; - invocationCallOrder: Array; + calls: Y[]; + instances: T[]; + invocationCallOrder: number[]; /** * List of results of calls to the mock function. */ - results: Array; + results: MockFunctionResult[]; }; type MockFunctionConfig = { @@ -75,8 +75,8 @@ type MockFunctionConfig = { defaultReturnValue: unknown; mockImpl: Function | undefined; mockName: string; - specificReturnValues: Array; - specificMockImpls: Array; + specificReturnValues: unknown[]; + specificMockImpls: Function[]; }; // see https://github.com/Microsoft/TypeScript/issues/25215 @@ -385,7 +385,7 @@ class ModuleMockerClass { this._invocationCallCounter = 1; } - private _getSlots(object?: Object): Array { + private _getSlots(object?: Object): string[] { if (!object) { return []; } @@ -481,7 +481,7 @@ class ModuleMockerClass { private _makeComponent( metadata: JestMock.MockFunctionMetadata, restore?: () => void, - ): Array; + ): unknown[]; private _makeComponent( metadata: JestMock.MockFunctionMetadata, restore?: () => void, @@ -501,7 +501,7 @@ class ModuleMockerClass { private _makeComponent( metadata: JestMock.MockFunctionMetadata, restore?: () => void, - ): Object | Array | RegExp | T | undefined | Mock { + ): Object | unknown[] | RegExp | T | undefined | Mock { if (metadata.type === 'object') { return new this._environmentGlobal.Object(); } else if (metadata.type === 'array') { @@ -806,15 +806,9 @@ class ModuleMockerClass { private _generateMock( metadata: JestMock.MockFunctionMetadata, - callbacks: Array, + callbacks: Function[], refs: { - [key: string]: - | Object - | Array - | RegExp - | T - | undefined - | Mock; + [key: string]: Object | unknown[] | RegExp | T | undefined | Mock; }, ): Mock { // metadata not compatible but it's the same type, maybe problem with diff --git a/packages/jest-resolve-dependencies/src/index.ts b/packages/jest-resolve-dependencies/src/index.ts index 71719bc090a4..463ba925a7b0 100644 --- a/packages/jest-resolve-dependencies/src/index.ts +++ b/packages/jest-resolve-dependencies/src/index.ts @@ -40,13 +40,13 @@ class DependencyResolver { resolve( file: Config.Path, options?: Resolver.ResolveModuleConfig, - ): Array { + ): Config.Path[] { 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; } @@ -73,21 +73,21 @@ class DependencyResolver { paths: Set, filter: (file: Config.Path) => boolean, options?: Resolver.ResolveModuleConfig, - ): Array { + ): DependencyResolver.ResolvedModule[] { if (!paths.size) { return []; } const collectModules = ( related: Set, - moduleMap: Array, + moduleMap: DependencyResolver.ResolvedModule[], changed: Set, ) => { const visitedModules = new Set(); - const result: Array = []; + const result: DependencyResolver.ResolvedModule[] = []; 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)) @@ -124,7 +124,7 @@ class DependencyResolver { } } } - const modules: Array = []; + const modules: DependencyResolver.ResolvedModule[] = []; for (const file of this._hasteFS.getAbsoluteFileIterator()) { modules.push({ dependencies: this.resolve(file, options), @@ -138,7 +138,7 @@ class DependencyResolver { paths: Set, filter: (file: Config.Path) => boolean, options?: Resolver.ResolveModuleConfig, - ): Array { + ): Config.Path[] { return this.resolveInverseModuleMap(paths, filter, options).map( module => module.file, ); diff --git a/packages/jest-resolve/src/defaultResolver.ts b/packages/jest-resolve/src/defaultResolver.ts index 6cda0840d98e..4399f4334f54 100644 --- a/packages/jest-resolve/src/defaultResolver.ts +++ b/packages/jest-resolve/src/defaultResolver.ts @@ -16,9 +16,9 @@ type ResolverOptions = { basedir: Config.Path; browser?: boolean; defaultResolver: typeof defaultResolver; - extensions?: Array; - moduleDirectory?: Array; - paths?: Array; + extensions?: string[]; + moduleDirectory?: string[]; + paths?: Config.Path[]; rootDir?: Config.Path; }; diff --git a/packages/jest-resolve/src/index.ts b/packages/jest-resolve/src/index.ts index c08f54cb9eab..dc22eafb3097 100644 --- a/packages/jest-resolve/src/index.ts +++ b/packages/jest-resolve/src/index.ts @@ -18,9 +18,9 @@ import {ResolverConfig} from './types'; type FindNodeModuleConfig = { basedir: Config.Path; browser?: boolean; - extensions?: Array; - moduleDirectory?: Array; - paths?: Array; + extensions?: string[]; + moduleDirectory?: string[]; + paths?: Config.Path[]; resolver?: Config.Path; rootDir?: Config.Path; }; @@ -52,7 +52,7 @@ class Resolver { private readonly _moduleMap: ModuleMap; private readonly _moduleIDCache: {[key: string]: string}; private readonly _moduleNameCache: {[name: string]: Config.Path}; - private readonly _modulePathCache: {[path: string]: Array}; + private readonly _modulePathCache: {[path: string]: Config.Path[]}; private readonly _supportsNativePlatform: boolean; constructor(moduleMap: ModuleMap, options: ResolverConfig) { @@ -249,7 +249,7 @@ class Resolver { return null; } - getModulePaths(from: Config.Path): Array { + getModulePaths(from: Config.Path): Config.Path[] { if (!this._modulePathCache[from]) { const moduleDirectory = this._options.moduleDirectories; const paths = nodeModulesPaths(from, {moduleDirectory}); diff --git a/packages/jest-resolve/src/nodeModulesPaths.ts b/packages/jest-resolve/src/nodeModulesPaths.ts index 4526660808d6..73cd76da523e 100644 --- a/packages/jest-resolve/src/nodeModulesPaths.ts +++ b/packages/jest-resolve/src/nodeModulesPaths.ts @@ -12,8 +12,8 @@ import {Config} from '@jest/types'; import {sync as realpath} from 'realpath-native'; type NodeModulesPathsOptions = { - moduleDirectory?: Array; - paths?: Array; + moduleDirectory?: string[]; + paths?: Config.Path[]; }; export default function nodeModulesPaths( @@ -46,7 +46,7 @@ export default function nodeModulesPaths( physicalBasedir = basedirAbs; } - const paths: Array = [physicalBasedir]; + const paths: Config.Path[] = [physicalBasedir]; let parsed = path.parse(physicalBasedir); while (parsed.dir !== paths[paths.length - 1]) { paths.push(parsed.dir); @@ -65,7 +65,7 @@ export default function nodeModulesPaths( : path.join(prefix, aPath, moduleDir), ), ), - [] as Array, + [] as Config.Path[], ) .filter(dir => dir !== ''); diff --git a/packages/jest-resolve/src/types.ts b/packages/jest-resolve/src/types.ts index b765f0333107..dbab6e756431 100644 --- a/packages/jest-resolve/src/types.ts +++ b/packages/jest-resolve/src/types.ts @@ -10,12 +10,12 @@ import {Config} from '@jest/types'; export type ResolverConfig = { browser?: boolean; defaultPlatform?: string; - extensions: Array; + extensions: string[]; hasCoreModules: boolean; - moduleDirectories: Array; - moduleNameMapper?: Array; - modulePaths: Array; - platforms?: Array; + moduleDirectories: string[]; + moduleNameMapper?: ModuleNameMapperConfig[]; + modulePaths: Config.Path[]; + platforms?: string[]; resolver: Config.Path; rootDir: Config.Path; }; diff --git a/packages/jest-snapshot/src/State.ts b/packages/jest-snapshot/src/State.ts index c6fd06953b73..e23e139adbc0 100644 --- a/packages/jest-snapshot/src/State.ts +++ b/packages/jest-snapshot/src/State.ts @@ -43,7 +43,7 @@ export default class SnapshotState { private _updateSnapshot: Config.SnapshotUpdateState; private _snapshotData: SnapshotData; private _snapshotPath: Config.Path; - private _inlineSnapshots: Array; + private _inlineSnapshots: InlineSnapshot[]; private _uncheckedKeys: Set; private _getBabelTraverse: () => Function; private _getPrettier: () => null | any; @@ -142,7 +142,7 @@ export default class SnapshotState { return this._uncheckedKeys.size || 0; } - getUncheckedKeys(): Array { + getUncheckedKeys(): string[] { return Array.from(this._uncheckedKeys); } diff --git a/packages/jest-snapshot/src/inline_snapshots.ts b/packages/jest-snapshot/src/inline_snapshots.ts index 9468c1c4ec43..41921d997f74 100644 --- a/packages/jest-snapshot/src/inline_snapshots.ts +++ b/packages/jest-snapshot/src/inline_snapshots.ts @@ -57,7 +57,7 @@ export const saveInlineSnapshots = ( }; const saveSnapshotsForFile = ( - snapshots: Array, + snapshots: InlineSnapshot[], sourceFilePath: Config.Path, prettier: any, babelTraverse: Function, @@ -92,7 +92,7 @@ const saveSnapshotsForFile = ( const groupSnapshotsBy = ( createKey: (inlineSnapshot: InlineSnapshot) => string, -) => (snapshots: Array) => +) => (snapshots: InlineSnapshot[]) => snapshots.reduce<{[key: string]: InlineSnapshot[]}>( (object, inlineSnapshot) => { const key = createKey(inlineSnapshot); diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index 3d92b9f94cee..da5a6060cc5a 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -544,7 +544,7 @@ const calcIgnorePatternRegexp = ( return new RegExp(config.transformIgnorePatterns.join('|')); }; -const wrap = (content: string, ...extras: Array) => { +const wrap = (content: string, ...extras: string[]) => { const globals = new Set([ 'module', 'exports', diff --git a/packages/jest-types/src/Config.ts b/packages/jest-types/src/Config.ts index 85a5db4df75f..4dd614acf3a4 100644 --- a/packages/jest-types/src/Config.ts +++ b/packages/jest-types/src/Config.ts @@ -13,8 +13,8 @@ export type HasteConfig = { computeSha1?: boolean; defaultPlatform?: string | null | undefined; hasteImplModulePath?: string; - platforms?: Array; - providesModuleNodeModules: Array; + platforms?: string[]; + providesModuleNodeModules: string[]; }; export type ReporterConfig = [string, Object]; @@ -30,10 +30,10 @@ export type DefaultOptions = { changedFilesWithAncestor: boolean; clearMocks: boolean; collectCoverage: boolean; - collectCoverageFrom: Array | null | undefined; + collectCoverageFrom: string[] | null | undefined; coverageDirectory: string | null | undefined; - coveragePathIgnorePatterns: Array; - coverageReporters: Array; + coveragePathIgnorePatterns: string[]; + coverageReporters: string[]; coverageThreshold: | { global: { @@ -47,43 +47,43 @@ export type DefaultOptions = { errorOnDeprecated: boolean; expand: boolean; filter: Path | null | undefined; - forceCoverageMatch: Array; + forceCoverageMatch: Glob[]; globals: ConfigGlobals; globalSetup: string | null | undefined; globalTeardown: string | null | undefined; haste: HasteConfig; maxConcurrency: number; - moduleDirectories: Array; - moduleFileExtensions: Array; + moduleDirectories: string[]; + moduleFileExtensions: string[]; moduleNameMapper: { [key: string]: string; }; - modulePathIgnorePatterns: Array; + modulePathIgnorePatterns: string[]; noStackTrace: boolean; notify: boolean; notifyMode: string; preset: string | null | undefined; prettierPath: string | null | undefined; - projects: Array | null | undefined; + projects: (string | ProjectConfig)[] | null | undefined; resetMocks: boolean; resetModules: boolean; resolver: Path | null | undefined; restoreMocks: boolean; rootDir: Path | null | undefined; - roots: Array | null | undefined; + roots: Path[] | null | undefined; runner: string; runTestsByPath: boolean; - setupFiles: Array; - setupFilesAfterEnv: Array; + setupFiles: Path[]; + setupFilesAfterEnv: Path[]; skipFilter: boolean; - snapshotSerializers: Array; + snapshotSerializers: Path[]; testEnvironment: string; testEnvironmentOptions: Object; testFailureExitCode: string | number; testLocationInResults: boolean; - testMatch: Array; - testPathIgnorePatterns: Array; - testRegex: Array; + testMatch: Glob[]; + testPathIgnorePatterns: string[]; + testRegex: string[]; testResultsProcessor: string | null | undefined; testRunner: string | null | undefined; testURL: string; @@ -94,8 +94,8 @@ export type DefaultOptions = { } | null | undefined; - transformIgnorePatterns: Array; - watchPathIgnorePatterns: Array; + transformIgnorePatterns: Glob[]; + watchPathIgnorePatterns: string[]; useStderr: boolean; verbose: boolean | null | undefined; watch: boolean; @@ -112,13 +112,13 @@ export type InitialOptions = { changedFilesWithAncestor?: boolean; changedSince?: string; collectCoverage?: boolean; - collectCoverageFrom?: Array; + collectCoverageFrom?: Glob[]; collectCoverageOnlyFrom?: { [key: string]: boolean; }; coverageDirectory?: string; - coveragePathIgnorePatterns?: Array; - coverageReporters?: Array; + coveragePathIgnorePatterns?: string[]; + coverageReporters?: string[]; coverageThreshold?: { global: { [key: string]: number; @@ -129,30 +129,30 @@ export type InitialOptions = { detectOpenHandles?: boolean; displayName?: string; expand?: boolean; - extraGlobals?: Array; + extraGlobals?: string[]; filter?: Path; findRelatedTests?: boolean; - forceCoverageMatch?: Array; + forceCoverageMatch?: Glob[]; forceExit?: boolean; json?: boolean; globals?: ConfigGlobals; globalSetup?: string | null | undefined; globalTeardown?: string | null | undefined; haste?: HasteConfig; - reporters?: Array; + reporters?: (string | ReporterConfig)[]; logHeapUsage?: boolean; lastCommit?: boolean; listTests?: boolean; mapCoverage?: boolean; maxConcurrency?: number; - moduleDirectories?: Array; - moduleFileExtensions?: Array; + moduleDirectories?: string[]; + moduleFileExtensions?: string[]; moduleLoader?: Path; moduleNameMapper?: { [key: string]: string; }; - modulePathIgnorePatterns?: Array; - modulePaths?: Array; + modulePathIgnorePatterns?: string[]; + modulePaths?: string[]; name?: string; noStackTrace?: boolean; notify?: boolean; @@ -160,38 +160,38 @@ export type InitialOptions = { onlyChanged?: boolean; outputFile?: Path; passWithNoTests?: boolean; - preprocessorIgnorePatterns?: Array; + preprocessorIgnorePatterns?: Glob[]; preset?: string | null | undefined; prettierPath?: string | null | undefined; - projects?: Array; + projects?: Glob[]; replname?: string | null | undefined; resetMocks?: boolean; resetModules?: boolean; resolver?: Path | null | undefined; restoreMocks?: boolean; rootDir: Path; - roots?: Array; + roots?: Path[]; runner?: string; runTestsByPath?: boolean; scriptPreprocessor?: string; - setupFiles?: Array; + setupFiles?: Path[]; setupTestFrameworkScriptFile?: Path; - setupFilesAfterEnv?: Array; + setupFilesAfterEnv?: Path[]; silent?: boolean; skipFilter?: boolean; skipNodeResolution?: boolean; snapshotResolver?: Path; - snapshotSerializers?: Array; + snapshotSerializers?: Path[]; errorOnDeprecated?: boolean; testEnvironment?: string; testEnvironmentOptions?: Object; testFailureExitCode?: string | number; testLocationInResults?: boolean; - testMatch?: Array; + testMatch?: Glob[]; testNamePattern?: string; - testPathDirs?: Array; - testPathIgnorePatterns?: Array; - testRegex?: string | Array; + testPathDirs?: Path[]; + testPathIgnorePatterns?: string[]; + testRegex?: string | string[]; testResultsProcessor?: string | null | undefined; testRunner?: string; testURL?: string; @@ -199,16 +199,16 @@ export type InitialOptions = { transform?: { [key: string]: string; }; - transformIgnorePatterns?: Array; - watchPathIgnorePatterns?: Array; - unmockedModulePathPatterns?: Array; + transformIgnorePatterns?: Glob[]; + watchPathIgnorePatterns?: string[]; + unmockedModulePathPatterns?: string[]; updateSnapshot?: boolean; useStderr?: boolean; verbose?: boolean | null | undefined; watch?: boolean; watchAll?: boolean; watchman?: boolean; - watchPlugins?: Array; + watchPlugins?: (string | [string, Object])[]; }; export type SnapshotUpdateState = 'all' | 'new' | 'none'; @@ -226,7 +226,7 @@ export type GlobalConfig = { changedSince: string; changedFilesWithAncestor: boolean; collectCoverage: boolean; - collectCoverageFrom: Array; + collectCoverageFrom: Glob[]; collectCoverageOnlyFrom: | { [key: string]: boolean; @@ -234,8 +234,8 @@ export type GlobalConfig = { | null | undefined; coverageDirectory: string; - coveragePathIgnorePatterns?: Array; - coverageReporters: Array; + coveragePathIgnorePatterns?: string[]; + coverageReporters: string[]; coverageThreshold: { global: { [key: string]: number; @@ -252,7 +252,7 @@ export type GlobalConfig = { | null | undefined; expand: boolean; - extraGlobals: Array; + extraGlobals: string[]; filter: Path | null | undefined; findRelatedTests: boolean; forceExit: boolean; @@ -265,7 +265,7 @@ export type GlobalConfig = { maxConcurrency: number; maxWorkers: number; noStackTrace: boolean; - nonFlagArgs: Array; + nonFlagArgs: string[]; noSCM: boolean | null | undefined; notify: boolean; notifyMode: NotifyMode; @@ -273,9 +273,9 @@ export type GlobalConfig = { onlyChanged: boolean; onlyFailures: boolean; passWithNoTests: boolean; - projects: Array; + projects: Glob[]; replname: string | null | undefined; - reporters: Array; + reporters: (string | ReporterConfig)[]; runTestsByPath: boolean; rootDir: Path; silent: boolean; @@ -292,10 +292,10 @@ export type GlobalConfig = { watchAll: boolean; watchman: boolean; watchPlugins: - | Array<{ + | { path: string; config: Object; - }> + }[] | null | undefined; }; @@ -306,26 +306,26 @@ export type ProjectConfig = { cache: boolean; cacheDirectory: Path; clearMocks: boolean; - coveragePathIgnorePatterns: Array; + coveragePathIgnorePatterns: string[]; cwd: Path; dependencyExtractor?: string; detectLeaks: boolean; detectOpenHandles: boolean; displayName: string | null | undefined; errorOnDeprecated: boolean; - extraGlobals: Array; + extraGlobals: string[]; filter: Path | null | undefined; - forceCoverageMatch: Array; + forceCoverageMatch: Glob[]; globalSetup: string | null | undefined; globalTeardown: string | null | undefined; globals: ConfigGlobals; haste: HasteConfig; - moduleDirectories: Array; - moduleFileExtensions: Array; + moduleDirectories: string[]; + moduleFileExtensions: string[]; moduleLoader: Path; - moduleNameMapper: Array<[string, string]>; - modulePathIgnorePatterns: Array; - modulePaths: Array; + moduleNameMapper: [string, string][]; + modulePathIgnorePatterns: string[]; + modulePaths: string[]; name: string; prettierPath: string; resetMocks: boolean; @@ -333,25 +333,25 @@ export type ProjectConfig = { resolver: Path | null | undefined; restoreMocks: boolean; rootDir: Path; - roots: Array; + roots: Path[]; runner: string; - setupFiles: Array; - setupFilesAfterEnv: Array; + setupFiles: Path[]; + setupFilesAfterEnv: Path[]; skipFilter: boolean; skipNodeResolution: boolean; snapshotResolver: Path | null | undefined; - snapshotSerializers: Array; + snapshotSerializers: Path[]; testEnvironment: string; testEnvironmentOptions: Object; - testMatch: Array; + testMatch: Glob[]; testLocationInResults: boolean; - testPathIgnorePatterns: Array; - testRegex: Array; + testPathIgnorePatterns: string[]; + testRegex: string[]; testRunner: string; testURL: string; timers: 'real' | 'fake'; - transform: Array<[string, Path]>; - transformIgnorePatterns: Array; - watchPathIgnorePatterns: Array; - unmockedModulePathPatterns: Array | null | undefined; + transform: [string, Path][]; + transformIgnorePatterns: Glob[]; + watchPathIgnorePatterns: string[]; + unmockedModulePathPatterns: string[] | null | undefined; }; diff --git a/packages/jest-types/src/Console.ts b/packages/jest-types/src/Console.ts index c85bef6639d3..32b5f0aec4c3 100644 --- a/packages/jest-types/src/Console.ts +++ b/packages/jest-types/src/Console.ts @@ -35,4 +35,4 @@ export type LogType = | 'time' | 'warn'; -export type ConsoleBuffer = Array; +export type ConsoleBuffer = LogEntry[]; diff --git a/packages/jest-types/src/Global.ts b/packages/jest-types/src/Global.ts index ed7739615e14..72b120f35066 100644 --- a/packages/jest-types/src/Global.ts +++ b/packages/jest-types/src/Global.ts @@ -22,7 +22,7 @@ export interface ItBase { export interface It extends ItBase { only: ItBase; skip: ItBase; - todo: (testName: TestName, ...rest: Array) => void; + todo: (testName: TestName, ...rest: any[]) => void; } export interface ItConcurrentBase { diff --git a/packages/jest-types/src/Matchers.ts b/packages/jest-types/src/Matchers.ts index f1a4b9b94ce9..b6245a75fccd 100644 --- a/packages/jest-types/src/Matchers.ts +++ b/packages/jest-types/src/Matchers.ts @@ -19,7 +19,7 @@ export type MatcherState = { equals: ( a: unknown, b: unknown, - customTesters?: Array, + customTesters?: Tester[], strictCheck?: boolean, ) => boolean; expand?: boolean; @@ -27,7 +27,7 @@ export type MatcherState = { isExpectingAssertions?: boolean; isNot: boolean; promise: string; - suppressedErrors: Array; + suppressedErrors: Error[]; testPath?: Path; // This is output from `jest-matcher-utils` plus iterableEquality, subsetEquality // Type it correctly when moving it to `expect` diff --git a/packages/jest-types/src/TestResult.ts b/packages/jest-types/src/TestResult.ts index c9434eae5a63..13718c629b6e 100644 --- a/packages/jest-types/src/TestResult.ts +++ b/packages/jest-types/src/TestResult.ts @@ -47,9 +47,9 @@ type Callsite = { }; export type AssertionResult = { - ancestorTitles: Array; + ancestorTitles: string[]; duration?: Milliseconds | null | undefined; - failureMessages: Array; + failureMessages: string[]; fullName: string; invocations?: number; location: Callsite | null | undefined; @@ -59,8 +59,8 @@ export type AssertionResult = { }; export type FormattedAssertionResult = { - ancestorTitles: Array; - failureMessages: Array | null; + ancestorTitles: string[]; + failureMessages: string[] | null; fullName: string; location: Callsite | null | undefined; status: Status; @@ -78,11 +78,11 @@ export type AggregatedResultWithoutCoverage = { numRuntimeErrorTestSuites: number; numTotalTests: number; numTotalTestSuites: number; - openHandles: Array; + openHandles: Error[]; snapshot: SnapshotSummary; startTime: number; success: boolean; - testResults: Array; + testResults: TestResult[]; wasInterrupted: boolean; }; @@ -92,8 +92,8 @@ export type AggregatedResult = AggregatedResultWithoutCoverage & { export type Suite = { title: string; - suites: Array; - tests: Array; + suites: Suite[]; + tests: AssertionResult[]; }; export type TestResult = { @@ -107,7 +107,7 @@ export type TestResult = { numPassingTests: number; numPendingTests: number; numTodoTests: number; - openHandles: Array; + openHandles: Error[]; perfStats: { end: Milliseconds; start: Milliseconds; @@ -118,7 +118,7 @@ export type TestResult = { fileDeleted: boolean; matched: number; unchecked: number; - uncheckedKeys: Array; + uncheckedKeys: string[]; unmatched: number; updated: number; }; @@ -127,7 +127,7 @@ export type TestResult = { }; testExecError?: SerializableError; testFilePath: string; - testResults: Array; + testResults: AssertionResult[]; }; export type FormattedTestResult = { @@ -138,7 +138,7 @@ export type FormattedTestResult = { startTime: number; endTime: number; coverage: any; - assertionResults: Array; + assertionResults: FormattedAssertionResult[]; }; export type FormattedTestResults = { @@ -155,7 +155,7 @@ export type FormattedTestResults = { snapshot: SnapshotSummary; startTime: number; success: boolean; - testResults: Array; + testResults: FormattedTestResult[]; wasInterrupted: boolean; }; @@ -168,7 +168,7 @@ export type CodeCoverageFormatter = ( export type UncheckedSnapshot = { filePath: string; - keys: Array; + keys: string[]; }; export type SnapshotSummary = { @@ -182,7 +182,7 @@ export type SnapshotSummary = { matched: number; total: number; unchecked: number; - uncheckedKeysByFile: Array; + uncheckedKeysByFile: UncheckedSnapshot[]; unmatched: number; updated: number; }; diff --git a/packages/jest-util/src/BufferedConsole.ts b/packages/jest-util/src/BufferedConsole.ts index 8312b314444f..5b915ddd55fd 100644 --- a/packages/jest-util/src/BufferedConsole.ts +++ b/packages/jest-util/src/BufferedConsole.ts @@ -86,23 +86,23 @@ export default class BufferedConsole extends Console { this._counters[label] = 0; } - debug(firstArg: any, ...rest: Array) { + debug(firstArg: any, ...rest: any[]) { this._log('debug', format(firstArg, ...rest)); } - dir(firstArg: any, ...rest: Array) { + dir(firstArg: any, ...rest: any[]) { this._log('dir', format(firstArg, ...rest)); } - dirxml(firstArg: any, ...rest: Array) { + dirxml(firstArg: any, ...rest: any[]) { this._log('dirxml', format(firstArg, ...rest)); } - error(firstArg: any, ...rest: Array) { + error(firstArg: any, ...rest: any[]) { this._log('error', format(firstArg, ...rest)); } - group(title?: string, ...rest: Array) { + group(title?: string, ...rest: any[]) { this._groupDepth++; if (title || rest.length > 0) { @@ -110,7 +110,7 @@ export default class BufferedConsole extends Console { } } - groupCollapsed(title?: string, ...rest: Array) { + groupCollapsed(title?: string, ...rest: any[]) { this._groupDepth++; if (title || rest.length > 0) { @@ -124,11 +124,11 @@ export default class BufferedConsole extends Console { } } - info(firstArg: any, ...rest: Array) { + info(firstArg: any, ...rest: any[]) { this._log('info', format(firstArg, ...rest)); } - log(firstArg: any, ...rest: Array) { + log(firstArg: any, ...rest: any[]) { this._log('log', format(firstArg, ...rest)); } @@ -151,7 +151,7 @@ export default class BufferedConsole extends Console { } } - warn(firstArg: any, ...rest: Array) { + warn(firstArg: any, ...rest: any[]) { this._log('warn', format(firstArg, ...rest)); } diff --git a/packages/jest-util/src/CustomConsole.ts b/packages/jest-util/src/CustomConsole.ts index a2a3fb9a8950..d82ec7a28490 100644 --- a/packages/jest-util/src/CustomConsole.ts +++ b/packages/jest-util/src/CustomConsole.ts @@ -68,23 +68,23 @@ export default class CustomConsole extends Console { this._counters[label] = 0; } - debug(firstArg: any, ...args: Array) { + debug(firstArg: any, ...args: any[]) { this._log('debug', format(firstArg, ...args)); } - dir(firstArg: any, ...args: Array) { + dir(firstArg: any, ...args: any[]) { this._log('dir', format(firstArg, ...args)); } - dirxml(firstArg: any, ...args: Array) { + dirxml(firstArg: any, ...args: any[]) { this._log('dirxml', format(firstArg, ...args)); } - error(firstArg: any, ...args: Array) { + error(firstArg: any, ...args: any[]) { this._log('error', format(firstArg, ...args)); } - group(title?: string, ...args: Array) { + group(title?: string, ...args: any[]) { this._groupDepth++; if (title || args.length > 0) { @@ -92,7 +92,7 @@ export default class CustomConsole extends Console { } } - groupCollapsed(title?: string, ...args: Array) { + groupCollapsed(title?: string, ...args: any[]) { this._groupDepth++; if (title || args.length > 0) { @@ -106,11 +106,11 @@ export default class CustomConsole extends Console { } } - info(firstArg: any, ...args: Array) { + info(firstArg: any, ...args: any[]) { this._log('info', format(firstArg, ...args)); } - log(firstArg: any, ...args: Array) { + log(firstArg: any, ...args: any[]) { this._log('log', format(firstArg, ...args)); } @@ -133,7 +133,7 @@ export default class CustomConsole extends Console { } } - warn(firstArg: any, ...args: Array) { + warn(firstArg: any, ...args: any[]) { this._log('warn', format(firstArg, ...args)); } diff --git a/packages/jest-util/src/FakeTimers.ts b/packages/jest-util/src/FakeTimers.ts index aea4916981b5..a74b8c9f6d1d 100644 --- a/packages/jest-util/src/FakeTimers.ts +++ b/packages/jest-util/src/FakeTimers.ts @@ -57,11 +57,11 @@ export default class FakeTimers { private _disposed?: boolean; private _fakeTimerAPIs!: TimerAPI; private _global: NodeJS.Global; - private _immediates!: Array; + private _immediates!: Tick[]; private _maxLoops: number; private _moduleMocker: ModuleMocker; private _now!: number; - private _ticks!: Array; + private _ticks!: Tick[]; private _timerAPIs: TimerAPI; private _timers!: {[key: string]: Timer}; private _uuidCounter: number; @@ -381,7 +381,7 @@ export default class FakeTimers { this._cancelledImmediates[uuid] = true; } - private _fakeNextTick(callback: Callback, ...args: Array) { + private _fakeNextTick(callback: Callback, ...args: any[]) { if (this._disposed) { return; } @@ -403,7 +403,7 @@ export default class FakeTimers { }); } - private _fakeSetImmediate(callback: Callback, ...args: Array) { + private _fakeSetImmediate(callback: Callback, ...args: any[]) { if (this._disposed) { return null; } @@ -430,7 +430,7 @@ export default class FakeTimers { private _fakeSetInterval( callback: Callback, intervalDelay?: number, - ...args: Array + ...args: any[] ) { if (this._disposed) { return null; @@ -452,11 +452,7 @@ export default class FakeTimers { return this._timerConfig.idToRef(uuid); } - private _fakeSetTimeout( - callback: Callback, - delay?: number, - ...args: Array - ) { + private _fakeSetTimeout(callback: Callback, delay?: number, ...args: any[]) { if (this._disposed) { return null; } diff --git a/packages/jest-util/src/__tests__/fakeTimers.test.ts b/packages/jest-util/src/__tests__/fakeTimers.test.ts index 7d53b0c91e51..3388cc837741 100644 --- a/packages/jest-util/src/__tests__/fakeTimers.test.ts +++ b/packages/jest-util/src/__tests__/fakeTimers.test.ts @@ -146,7 +146,7 @@ describe('FakeTimers', () => { }); timers.useFakeTimers(); - const runOrder: Array = []; + const runOrder: string[] = []; const mock1 = jest.fn(() => runOrder.push('mock1')); const mock2 = jest.fn(() => runOrder.push('mock2')); @@ -394,7 +394,7 @@ describe('FakeTimers', () => { }); timers.useFakeTimers(); - const runOrder: Array = []; + const runOrder: string[] = []; const mock1 = jest.fn(() => runOrder.push('mock1')); const mock2 = jest.fn(() => runOrder.push('mock2')); const mock3 = jest.fn(() => runOrder.push('mock3')); @@ -580,7 +580,7 @@ describe('FakeTimers', () => { }); timers.useFakeTimers(); - const runOrder: Array = []; + const runOrder: string[] = []; const mock1 = jest.fn(() => runOrder.push('mock1')); const mock2 = jest.fn(() => runOrder.push('mock2')); const mock3 = jest.fn(() => runOrder.push('mock3')); @@ -754,7 +754,7 @@ describe('FakeTimers', () => { }); timers.useFakeTimers(); - const runOrder: Array = []; + const runOrder: string[] = []; global.setTimeout(function cb() { runOrder.push('mock1'); diff --git a/packages/jest-util/src/deepCyclicCopy.ts b/packages/jest-util/src/deepCyclicCopy.ts index 465ce9f3f1e0..e58d4ccc89f5 100644 --- a/packages/jest-util/src/deepCyclicCopy.ts +++ b/packages/jest-util/src/deepCyclicCopy.ts @@ -18,7 +18,7 @@ if (!Object.getOwnPropertyDescriptors) { Object.getOwnPropertyDescriptors = obj => { const list: {[key: string]: PropertyDescriptor | undefined} = {}; - (Object.getOwnPropertyNames(obj) as Array) + (Object.getOwnPropertyNames(obj) as (string | symbol)[]) .concat(Object.getOwnPropertySymbols(obj)) .forEach(key => { // @ts-ignore: assignment with a Symbol is OK. @@ -81,7 +81,7 @@ function deepCyclicCopyObject( } function deepCyclicCopyArray( - array: Array, + array: T[], options: DeepCyclicCopyOptions, cycles: WeakMap, ): T { diff --git a/packages/jest-util/src/getFailedSnapshotTests.ts b/packages/jest-util/src/getFailedSnapshotTests.ts index 192fa524a4b7..742e98d57351 100644 --- a/packages/jest-util/src/getFailedSnapshotTests.ts +++ b/packages/jest-util/src/getFailedSnapshotTests.ts @@ -8,7 +8,7 @@ import {Config, TestResult} from '@jest/types'; function getFailedSnapshotTests(testResults: TestResult.AggregatedResult) { - const failedTestPaths: Array = []; + const failedTestPaths: Config.Path[] = []; if (testResults.numFailedTests === 0 || !testResults.testResults) { return failedTestPaths; } diff --git a/packages/jest-util/src/installCommonGlobals.ts b/packages/jest-util/src/installCommonGlobals.ts index 17c87ff980db..ef71a29603e2 100644 --- a/packages/jest-util/src/installCommonGlobals.ts +++ b/packages/jest-util/src/installCommonGlobals.ts @@ -56,7 +56,7 @@ export default function( // Forward some APIs. DTRACE.forEach(dtrace => { // @ts-ignore: no index - globalObject[dtrace] = function(...args: Array) { + globalObject[dtrace] = function(...args: any[]) { // @ts-ignore: no index return global[dtrace].apply(this, args); }; diff --git a/packages/jest-watcher/src/JestHooks.ts b/packages/jest-watcher/src/JestHooks.ts index 5f8cad6b775c..e73fb3d9e2ed 100644 --- a/packages/jest-watcher/src/JestHooks.ts +++ b/packages/jest-watcher/src/JestHooks.ts @@ -20,9 +20,9 @@ type AvailableHooks = class JestHooks { private _listeners: { - onFileChange: Array; - onTestRunComplete: Array; - shouldRunTestSuite: Array; + onFileChange: FileChange[]; + onTestRunComplete: TestRunComplete[]; + shouldRunTestSuite: ShouldRunTestSuite[]; }; constructor() { diff --git a/packages/jest-watcher/src/types.ts b/packages/jest-watcher/src/types.ts index 8886c011cd1f..1b6d01acfe13 100644 --- a/packages/jest-watcher/src/types.ts +++ b/packages/jest-watcher/src/types.ts @@ -14,10 +14,10 @@ type TestSuiteInfo = { }; export type JestHookExposedFS = { - projects: Array<{ + projects: { config: Config.ProjectConfig; - testPaths: Array; - }>; + testPaths: Config.Path[]; + }[]; }; export type FileChange = (fs: JestHookExposedFS) => void; diff --git a/packages/jest-worker/src/Farm.ts b/packages/jest-worker/src/Farm.ts index 522561fdfec0..271945f3c00e 100644 --- a/packages/jest-worker/src/Farm.ts +++ b/packages/jest-worker/src/Farm.ts @@ -20,11 +20,11 @@ export default class Farm { private _computeWorkerKey: FarmOptions['computeWorkerKey']; private _cacheKeys: {[key: string]: WorkerInterface}; private _callback: Function; - private _last: Array; - private _locks: Array; + private _last: QueueItem[]; + private _locks: boolean[]; private _numOfWorkers: number; private _offset: number; - private _queue: Array; + private _queue: (QueueItem | null)[]; constructor( numOfWorkers: number, @@ -44,7 +44,7 @@ export default class Farm { } } - doWork(method: string, ...args: Array): Promise { + doWork(method: string, ...args: any[]): Promise { return new Promise((resolve, reject) => { const computeWorkerKey = this._computeWorkerKey; const request: ChildMessage = [CHILD_MESSAGE_CALL, false, method, args]; diff --git a/packages/jest-worker/src/base/BaseWorkerPool.ts b/packages/jest-worker/src/base/BaseWorkerPool.ts index 8ce0878e105a..616b9ebbc253 100644 --- a/packages/jest-worker/src/base/BaseWorkerPool.ts +++ b/packages/jest-worker/src/base/BaseWorkerPool.ts @@ -22,7 +22,7 @@ export default class BaseWorkerPool { private readonly _stderr: NodeJS.ReadableStream; private readonly _stdout: NodeJS.ReadableStream; protected readonly _options: WorkerPoolOptions; - private readonly _workers: Array; + private readonly _workers: WorkerInterface[]; constructor(workerPath: string, options: WorkerPoolOptions) { this._options = options; @@ -73,7 +73,7 @@ export default class BaseWorkerPool { return this._stdout; } - getWorkers(): Array { + getWorkers(): WorkerInterface[] { return this._workers; } diff --git a/packages/jest-worker/src/index.ts b/packages/jest-worker/src/index.ts index 6e8aa4f839ba..575ae51e5ffb 100644 --- a/packages/jest-worker/src/index.ts +++ b/packages/jest-worker/src/index.ts @@ -113,10 +113,7 @@ export default class JestWorker { }); } - private _callFunctionWithArgs( - method: string, - ...args: Array - ): Promise { + private _callFunctionWithArgs(method: string, ...args: any[]): Promise { if (this._ending) { throw new Error('Farm is ended, no more calls can be done to it'); } diff --git a/packages/jest-worker/src/types.ts b/packages/jest-worker/src/types.ts index f0f4d86aecae..f59992f7bde1 100644 --- a/packages/jest-worker/src/types.ts +++ b/packages/jest-worker/src/types.ts @@ -29,9 +29,9 @@ export type ForkOptions = { cwd?: string; env?: NodeJS.ProcessEnv; execPath?: string; - execArgv?: Array; + execArgv?: string[]; silent?: boolean; - stdio?: Array; + stdio?: any[]; uid?: number; gid?: number; }; @@ -39,7 +39,7 @@ export type ForkOptions = { export interface WorkerPoolInterface { getStderr(): NodeJS.ReadableStream; getStdout(): NodeJS.ReadableStream; - getWorkers(): Array; + getWorkers(): WorkerInterface[]; createWorker(options: WorkerOptions): WorkerInterface; send( workerId: number, @@ -64,10 +64,10 @@ export interface WorkerInterface { } export type FarmOptions = { - computeWorkerKey?: (method: string, ...args: Array) => string | null; + computeWorkerKey?: (method: string, ...args: unknown[]) => string | null; exposedMethods?: ReadonlyArray; forkOptions?: ForkOptions; - setupArgs?: Array; + setupArgs?: unknown[]; maxRetries?: number; numWorkers?: number; WorkerPool?: ( @@ -78,7 +78,7 @@ export type FarmOptions = { }; export type WorkerPoolOptions = { - setupArgs: Array; + setupArgs: unknown[]; forkOptions: ForkOptions; maxRetries: number; numWorkers: number; @@ -87,7 +87,7 @@ export type WorkerPoolOptions = { export type WorkerOptions = { forkOptions: ForkOptions; - setupArgs: Array; + setupArgs: unknown[]; maxRetries: number; workerId: number; workerPath: string; @@ -108,7 +108,7 @@ export type ChildMessageInitialize = [ typeof CHILD_MESSAGE_INITIALIZE, // type boolean, // processed string, // file - Array | undefined, // setupArgs + unknown[] | undefined, // setupArgs MessagePort | undefined // MessagePort ]; @@ -116,7 +116,7 @@ export type ChildMessageCall = [ typeof CHILD_MESSAGE_CALL, // type boolean, // processed string, // method - Array // args + unknown[] // args ]; export type ChildMessageEnd = [ diff --git a/packages/jest-worker/src/workers/processChild.ts b/packages/jest-worker/src/workers/processChild.ts index beb395af1a22..8c41922b9744 100644 --- a/packages/jest-worker/src/workers/processChild.ts +++ b/packages/jest-worker/src/workers/processChild.ts @@ -18,7 +18,7 @@ import { } from '../types'; let file: string | null = null; -let setupArgs: Array = []; +let setupArgs: unknown[] = []; let initialized = false; /** @@ -109,10 +109,10 @@ function exitProcess(): void { process.exit(0); } -function execMethod(method: string, args: Array): void { +function execMethod(method: string, args: any[]): void { const main = require(file!); - let fn: (...args: Array) => unknown; + let fn: (...args: unknown[]) => unknown; if (method === 'default') { fn = main.__esModule ? main['default'] : main; @@ -136,9 +136,9 @@ function execMethod(method: string, args: Array): void { } function execFunction( - fn: (...args: Array) => any | Promise, + fn: (...args: unknown[]) => any | Promise, ctx: unknown, - args: Array, + args: unknown[], onResult: (result: unknown) => void, onError: (error: Error) => void, ): void { diff --git a/packages/jest-worker/src/workers/threadChild.ts b/packages/jest-worker/src/workers/threadChild.ts index 4d8272cef8c0..f40ef3bf812f 100644 --- a/packages/jest-worker/src/workers/threadChild.ts +++ b/packages/jest-worker/src/workers/threadChild.ts @@ -22,7 +22,7 @@ import { } from '../types'; let file: string | null = null; -let setupArgs: Array = []; +let setupArgs: unknown[] = []; let initialized = false; /** @@ -112,10 +112,10 @@ function exitProcess(): void { process.exit(0); } -function execMethod(method: string, args: Array): void { +function execMethod(method: string, args: any[]): void { const main = require(file!); - let fn: (...args: Array) => unknown; + let fn: (...args: unknown[]) => unknown; if (method === 'default') { fn = main.__esModule ? main['default'] : main; @@ -139,9 +139,9 @@ function execMethod(method: string, args: Array): void { } function execFunction( - fn: (...args: Array) => any, + fn: (...args: unknown[]) => any, ctx: unknown, - args: Array, + args: unknown[], onResult: (result: unknown) => void, onError: (error: Error) => void, ): void { diff --git a/packages/pretty-format/src/__tests__/Immutable.test.ts b/packages/pretty-format/src/__tests__/Immutable.test.ts index 05c51241f804..6e0e95138937 100644 --- a/packages/pretty-format/src/__tests__/Immutable.test.ts +++ b/packages/pretty-format/src/__tests__/Immutable.test.ts @@ -866,7 +866,7 @@ describe('Immutable.Seq', () => { }); it('supports a non-empty sequence from arguments', () => { - function returnArguments(..._args: Array) { + function returnArguments(..._args: any[]) { return arguments; } expect(Immutable.Seq(returnArguments(0, 1, 2))).toPrettyPrintTo( @@ -956,7 +956,7 @@ describe('Immutable.Seq lazy values', () => { // undefined size confirms correct criteria for lazy Seq test('from iterator', () => { - function returnIterator(values: Array) { + function returnIterator(values: string[]) { let i = 0; return { next() { diff --git a/packages/pretty-format/src/__tests__/prettyFormat.test.ts b/packages/pretty-format/src/__tests__/prettyFormat.test.ts index 779d3c45a754..3b6c7f0f8d88 100644 --- a/packages/pretty-format/src/__tests__/prettyFormat.test.ts +++ b/packages/pretty-format/src/__tests__/prettyFormat.test.ts @@ -7,7 +7,7 @@ import prettyFormat from '../'; -function returnArguments(..._args: Array) { +function returnArguments(..._args: unknown[]) { return arguments; } diff --git a/packages/pretty-format/src/collections.ts b/packages/pretty-format/src/collections.ts index 305e5c0da3d6..9f81d5fb9d92 100644 --- a/packages/pretty-format/src/collections.ts +++ b/packages/pretty-format/src/collections.ts @@ -9,7 +9,7 @@ import {Config, Printer, Refs} from './types'; const getKeysOfEnumerableProperties = (object: Object) => { - const keys: Array = Object.keys(object).sort(); + const keys: (string | symbol)[] = Object.keys(object).sort(); if (Object.getOwnPropertySymbols) { Object.getOwnPropertySymbols(object).forEach(symbol => { diff --git a/packages/pretty-format/src/plugins/ReactTestComponent.ts b/packages/pretty-format/src/plugins/ReactTestComponent.ts index c380fbfc3e81..4cfdb99261ba 100644 --- a/packages/pretty-format/src/plugins/ReactTestComponent.ts +++ b/packages/pretty-format/src/plugins/ReactTestComponent.ts @@ -11,7 +11,7 @@ export type ReactTestObject = { $$typeof: Symbol; type: string; props?: Object; - children?: null | Array; + children?: null | ReactTestChild[]; }; // Child can be `number` in Stack renderer but not in Fiber renderer. diff --git a/packages/pretty-format/src/plugins/lib/markup.ts b/packages/pretty-format/src/plugins/lib/markup.ts index c5ab6a786091..297f797834fd 100644 --- a/packages/pretty-format/src/plugins/lib/markup.ts +++ b/packages/pretty-format/src/plugins/lib/markup.ts @@ -11,7 +11,7 @@ import escapeHTML from './escapeHTML'; // Return empty string if keys is empty. export const printProps = ( - keys: Array, + keys: string[], props: any, config: Config, indentation: string, @@ -55,7 +55,7 @@ export const printProps = ( // Return empty string if children is empty. export const printChildren = ( - children: Array, + children: any[], config: Config, indentation: string, depth: number, diff --git a/packages/pretty-format/src/types.ts b/packages/pretty-format/src/types.ts index 89d06d5bd418..a7cad7703a31 100644 --- a/packages/pretty-format/src/types.ts +++ b/packages/pretty-format/src/types.ts @@ -13,7 +13,7 @@ export type Colors = { value: {close: string; open: string}; }; type Indent = (arg0: string) => string; -export type Refs = Array; +export type Refs = any[]; type Print = (arg0: any) => string; export type Theme = { @@ -114,4 +114,4 @@ type OldPlugin = { export type Plugin = NewPlugin | OldPlugin; -export type Plugins = Array; +export type Plugins = Plugin[];