From d9fac539681407efbd3c3c755a1e07b5f0c658a0 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Mon, 14 Sep 2020 13:33:44 +0200 Subject: [PATCH 1/5] chore: get rid of some `any`s --- e2e/Utils.ts | 4 +-- .../src/__tests__/index.test.ts | 25 +++++++++++-------- packages/diff-sequences/src/index.ts | 9 +++---- .../expect/src/__tests__/spyMatchers.test.ts | 4 +-- packages/expect/src/asymmetricMatchers.ts | 8 +++--- .../jestAdapterInit.ts | 2 +- packages/jest-circus/src/utils.ts | 4 +-- .../jest-cli/src/init/generate_config_file.ts | 2 +- packages/jest-config/src/normalize.ts | 4 +-- .../src/__tests__/watch-file-changes.test.ts | 10 ++++---- packages/jest-each/src/validation.ts | 2 +- packages/jest-haste-map/src/ModuleMap.ts | 2 +- packages/jest-haste-map/src/index.ts | 4 +-- packages/jest-jasmine2/src/PCancelable.ts | 4 +-- .../src/jasmine/ReportDispatcher.ts | 2 +- .../jest-jasmine2/src/jasmine/createSpy.ts | 4 +-- packages/jest-jasmine2/src/queueRunner.ts | 2 +- packages/jest-jasmine2/src/treeProcessor.ts | 10 ++++---- packages/jest-jasmine2/src/types.ts | 6 ++--- .../jest-matcher-utils/src/Replaceable.ts | 8 ++++-- .../deepCyclicCopyReplaceable.test.ts | 2 +- .../src/__tests__/index.test.ts | 1 - .../__tests__/printDiffOrStringify.test.ts | 24 +++++++++--------- .../src/deepCyclicCopyReplaceable.ts | 14 +++++++---- packages/jest-matcher-utils/src/index.ts | 4 +-- packages/jest-repl/src/cli/repl.ts | 4 +-- .../src/__tests__/notify_reporter.test.ts | 2 +- .../jest-reporters/src/default_reporter.ts | 2 +- .../jest-reporters/src/notify_reporter.ts | 7 +++--- packages/jest-reporters/src/types.ts | 7 ++++-- .../src/__tests__/dependency_resolver.test.ts | 5 ++-- .../__tests__/runtime_require_resolve.test.ts | 6 ++--- packages/jest-runtime/src/index.ts | 10 ++++---- packages/jest-serializer/src/index.ts | 4 +-- .../src/__tests__/matcher.test.ts | 2 +- .../src/__tests__/printSnapshot.test.ts | 2 +- packages/jest-snapshot/src/printSnapshot.ts | 2 +- packages/jest-snapshot/src/types.ts | 2 +- .../src/__tests__/getCallsite.test.ts | 2 +- packages/jest-test-result/src/types.ts | 12 ++++----- .../jest-transform/src/ScriptTransformer.ts | 2 +- packages/jest-types/src/Circus.ts | 4 +-- packages/jest-types/src/Config.ts | 10 ++++---- .../__tests__/installCommonGlobals.test.ts | 2 +- packages/jest-util/src/createProcessObject.ts | 10 ++++---- packages/jest-validate/src/condition.ts | 2 +- packages/jest-validate/src/deprecated.ts | 2 +- packages/jest-validate/src/errors.ts | 2 +- packages/jest-validate/src/types.ts | 16 ++++++------ packages/jest-validate/src/validate.ts | 4 +-- packages/jest-validate/src/warnings.ts | 4 +-- packages/jest-worker/src/index.ts | 4 +-- .../jest-worker/src/workers/processChild.ts | 15 +++++++---- .../jest-worker/src/workers/threadChild.ts | 13 +++++++--- .../src/__tests__/AsymmetricMatcher.test.ts | 2 +- .../src/__tests__/Immutable.test.ts | 2 +- .../src/__tests__/ReactElement.test.ts | 2 +- .../src/__tests__/prettyFormat.test.ts | 14 +++++------ .../src/__tests__/react.test.tsx | 18 ++++++------- .../src/__tests__/setPrettyPrint.ts | 8 ++++-- packages/pretty-format/src/collections.ts | 2 +- packages/pretty-format/src/index.ts | 9 ++++--- .../pretty-format/src/plugins/lib/markup.ts | 2 +- .../src/alignedAnsiStyleSerializer.ts | 3 ++- 64 files changed, 204 insertions(+), 178 deletions(-) diff --git a/e2e/Utils.ts b/e2e/Utils.ts index 9c84b83f035a..547622a64d8d 100644 --- a/e2e/Utils.ts +++ b/e2e/Utils.ts @@ -65,7 +65,7 @@ export const linkJestPackage = (packageName: string, cwd: Config.Path) => { export const makeTemplate = ( str: string, -): ((values?: Array) => string) => (values?: Array) => +): ((values?: Array) => string) => (values?: unknown) => str.replace(/\$(\d+)/g, (_match, number) => { if (!Array.isArray(values)) { throw new Error('Array of values must be passed to the template.'); @@ -168,7 +168,7 @@ export const sortLines = (output: string) => export const createEmptyPackage = ( directory: Config.Path, - packageJson?: {[keys: string]: any}, + packageJson?: {[keys: string]: unknown}, ) => { const DEFAULT_PACKAGE_JSON = { description: 'THIS IS AN AUTOGENERATED FILE AND SHOULD NOT BE ADDED TO GIT', diff --git a/packages/diff-sequences/src/__tests__/index.test.ts b/packages/diff-sequences/src/__tests__/index.test.ts index 6652c756b7fb..76eceac645c6 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: Array, b: Array): number => { let n = 0; diff( a.length, @@ -75,7 +75,10 @@ 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: Array, + b: Array, +): number => { let n = 0; diff( a.length, @@ -133,8 +136,8 @@ const assertEnd = (name: string, val: number, end: number) => { }; const assertCommonItems = ( - a: Array | string, - b: Array | string, + a: Array | string, + b: Array | string, nCommon: number, aCommon: number, bCommon: number, @@ -192,9 +195,9 @@ const countDifferences = ( // Return array of items in a longest common subsequence of array-like objects. const findCommonItems = ( - a: Array | string, - b: Array | string, -): Array => { + a: Array | string, + b: Array | string, +): Array => { const aLength = a.length; const bLength = b.length; const isCommon = (aIndex: number, bIndex: number) => { @@ -205,7 +208,7 @@ const findCommonItems = ( return a[aIndex] === b[bIndex]; }; - const array = []; + const array: Array = []; diff( aLength, bLength, @@ -231,9 +234,9 @@ const findCommonItems = ( // Assert that array-like objects have the expected common items. const expectCommonItems = ( - a: Array | string, - b: Array | string, - expected: Array, + a: Array | string, + b: Array | string, + expected: Array, ) => { expect(findCommonItems(a, b)).toEqual(expected); diff --git a/packages/diff-sequences/src/index.ts b/packages/diff-sequences/src/index.ts index 5426c242ce0a..cdbfe305b574 100644 --- a/packages/diff-sequences/src/index.ts +++ b/packages/diff-sequences/src/index.ts @@ -756,10 +756,9 @@ const findSubsequences = ( } }; -const validateLength = (name: string, arg: any) => { - const type = typeof arg; - if (type !== 'number') { - throw new TypeError(`${pkg}: ${name} typeof ${type} is not a number`); +const validateLength = (name: string, arg: unknown) => { + if (typeof arg !== 'number') { + throw new TypeError(`${pkg}: ${name} typeof ${typeof arg} is not a number`); } if (!Number.isSafeInteger(arg)) { throw new RangeError(`${pkg}: ${name} value ${arg} is not a safe integer`); @@ -769,7 +768,7 @@ const validateLength = (name: string, arg: any) => { } }; -const validateCallback = (name: string, arg: any) => { +const validateCallback = (name: string, arg: unknown) => { const type = typeof arg; if (type !== 'function') { throw new TypeError(`${pkg}: ${name} typeof ${type} is not a function`); diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index cebf5682e198..a6906851860e 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -179,7 +179,7 @@ const createSpy = (fn: jest.Mock) => { ].forEach(calledWith => { const caller = function ( callee: (...a: Array) => void, - ...args: any + ...args: Array ) { if ( calledWith === 'nthCalledWith' || @@ -739,7 +739,7 @@ const createSpy = (fn: jest.Mock) => { ].forEach(returnedWith => { const caller = function ( callee: (...a: Array) => void, - ...args: any + ...args: Array ) { if ( returnedWith === 'nthReturnedWith' || diff --git a/packages/expect/src/asymmetricMatchers.ts b/packages/expect/src/asymmetricMatchers.ts index 7f9801602fcd..a12436160f96 100644 --- a/packages/expect/src/asymmetricMatchers.ts +++ b/packages/expect/src/asymmetricMatchers.ts @@ -148,8 +148,8 @@ class ArrayContaining extends AsymmetricMatcher> { } } -class ObjectContaining extends AsymmetricMatcher> { - constructor(sample: Record, inverse: boolean = false) { +class ObjectContaining extends AsymmetricMatcher> { + constructor(sample: Record, inverse: boolean = false) { super(sample); this.inverse = inverse; } @@ -255,10 +255,10 @@ export const arrayContaining = (sample: Array): ArrayContaining => export const arrayNotContaining = (sample: Array): ArrayContaining => new ArrayContaining(sample, true); export const objectContaining = ( - sample: Record, + sample: Record, ): ObjectContaining => new ObjectContaining(sample); export const objectNotContaining = ( - sample: Record, + sample: Record, ): ObjectContaining => new ObjectContaining(sample, true); export const stringContaining = (expected: string): StringContaining => new StringContaining(expected); 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 96651b7337d0..2e0f38f08d13 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts @@ -54,7 +54,7 @@ export const initialize = async ({ getPrettier: () => null | any; getBabelTraverse: () => typeof BabelTraverse; globalConfig: Config.GlobalConfig; - localRequire: (path: Config.Path) => any; + localRequire: (path: Config.Path) => T; testPath: Config.Path; parentProcess: Process; sendMessageToJest?: TestFileEvent; diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts index 82b4b78e52d4..58fab0d82286 100644 --- a/packages/jest-circus/src/utils.ts +++ b/packages/jest-circus/src/utils.ts @@ -151,7 +151,7 @@ const _makeTimeoutMessage = (timeout: number, isHook: boolean) => // the original values in the variables before we require any files. const {setTimeout, clearTimeout} = global; -function checkIsError(error: any): error is Error { +function checkIsError(error: unknown): error is Error { return !!(error && (error as Error).message && (error as Error).stack); } @@ -160,7 +160,7 @@ export const callAsyncCircusFn = ( testContext: Circus.TestContext | undefined, asyncError: Circus.Exception, {isHook, timeout}: {isHook?: boolean | null; timeout: number}, -): Promise => { +): Promise => { let timeoutID: NodeJS.Timeout; let completed = false; diff --git a/packages/jest-cli/src/init/generate_config_file.ts b/packages/jest-cli/src/init/generate_config_file.ts index c968e2985e19..4d7f8a428c3f 100644 --- a/packages/jest-cli/src/init/generate_config_file.ts +++ b/packages/jest-cli/src/init/generate_config_file.ts @@ -37,7 +37,7 @@ const generateConfigFile = ( ): string => { const {coverage, coverageProvider, clearMocks, environment} = results; - const overrides: Record = {}; + const overrides: Record = {}; if (coverage) { Object.assign(overrides, { diff --git a/packages/jest-config/src/normalize.ts b/packages/jest-config/src/normalize.ts index d732abda33b0..fcd19c4db403 100644 --- a/packages/jest-config/src/normalize.ts +++ b/packages/jest-config/src/normalize.ts @@ -1007,9 +1007,9 @@ export default function normalize( newOptions.watchAll = false; } - // as any since it can happen. We really need to fix the types here + // as unknown since it can happen. We really need to fix the types here if ( - newOptions.moduleNameMapper === (DEFAULT_CONFIG.moduleNameMapper as any) + newOptions.moduleNameMapper === (DEFAULT_CONFIG.moduleNameMapper as unknown) ) { newOptions.moduleNameMapper = []; } diff --git a/packages/jest-core/src/__tests__/watch-file-changes.test.ts b/packages/jest-core/src/__tests__/watch-file-changes.test.ts index 17ed2fc5c370..ea953f7d7b4d 100644 --- a/packages/jest-core/src/__tests__/watch-file-changes.test.ts +++ b/packages/jest-core/src/__tests__/watch-file-changes.test.ts @@ -19,7 +19,7 @@ import type {AggregatedResult} from '@jest/test-result'; describe('Watch mode flows with changed files', () => { jest.resetModules(); - let watch: any; + let watch: unknown; let pipe: NodeJS.ReadStream; let stdin: MockStdin; const testDirectory = path.resolve(tmpdir(), 'jest-tmp'); @@ -33,7 +33,7 @@ describe('Watch mode flows with changed files', () => { beforeEach(() => { watch = require('../watch').default; - pipe = {write: jest.fn()} as any; + pipe = {write: jest.fn()} as unknown; stdin = new MockStdin(); rimraf.sync(cacheDirectory); rimraf.sync(testDirectory); @@ -79,7 +79,7 @@ describe('Watch mode flows with changed files', () => { watch: false, watchman: false, }, - {} as any, + {} as unknown, ).options; hasteMapInstance = await Runtime.createHasteMap(config, { @@ -165,7 +165,7 @@ describe('Watch mode flows with changed files', () => { }); class MockStdin { - private _callbacks: Array; + private _callbacks: Array; constructor() { this._callbacks = []; @@ -175,7 +175,7 @@ class MockStdin { setEncoding() {} - on(_: any, callback: any) { + on(_: unknown, callback: unknown) { this._callbacks.push(callback); } diff --git a/packages/jest-each/src/validation.ts b/packages/jest-each/src/validation.ts index ec68c91b65d2..7fb2df3c3cf2 100644 --- a/packages/jest-each/src/validation.ts +++ b/packages/jest-each/src/validation.ts @@ -46,7 +46,7 @@ export const validateArrayTable = (table: unknown): void => { }; const isTaggedTemplateLiteral = (array: any) => array.raw !== undefined; -const isEmptyTable = (table: Array) => table.length === 0; +const isEmptyTable = (table: Array) => table.length === 0; const isEmptyString = (str: string | unknown) => typeof str === 'string' && str.trim() === ''; diff --git a/packages/jest-haste-map/src/ModuleMap.ts b/packages/jest-haste-map/src/ModuleMap.ts index 6267cf51e41f..6719bf2d6c49 100644 --- a/packages/jest-haste-map/src/ModuleMap.ts +++ b/packages/jest-haste-map/src/ModuleMap.ts @@ -36,7 +36,7 @@ export default class ModuleMap { private json: SerializableModuleMap | undefined; private static mapToArrayRecursive( - map: Map, + map: Map, ): Array<[string, unknown]> { let arr = Array.from(map); if (arr[0] && arr[0][1] instanceof Map) { diff --git a/packages/jest-haste-map/src/index.ts b/packages/jest-haste-map/src/index.ts index 7720ad6bdacf..f0e4aa25e605 100644 --- a/packages/jest-haste-map/src/index.ts +++ b/packages/jest-haste-map/src/index.ts @@ -381,7 +381,7 @@ class HasteMap extends EventEmitter { let hasteMap: InternalHasteMap; try { - hasteMap = serializer.readFileSync(this._cachePath); + hasteMap = serializer.readFileSync(this._cachePath) as any; } catch { hasteMap = this._createEmptyMap(); } @@ -1111,7 +1111,7 @@ class DuplicateError extends Error { } } -function copy>(object: T): T { +function copy>(object: T): T { return Object.assign(Object.create(null), object); } diff --git a/packages/jest-jasmine2/src/PCancelable.ts b/packages/jest-jasmine2/src/PCancelable.ts index 91a2e537e756..8481cf8a397f 100644 --- a/packages/jest-jasmine2/src/PCancelable.ts +++ b/packages/jest-jasmine2/src/PCancelable.ts @@ -53,7 +53,7 @@ export default class PCancelable extends Promise { | undefined | null, onRejected?: - | ((reason: any) => TResult2 | PromiseLike) + | ((reason: unknown) => TResult2 | PromiseLike) | undefined | null, ): Promise { @@ -62,7 +62,7 @@ export default class PCancelable extends Promise { catch( onRejected?: - | ((reason: any) => TResult | PromiseLike) + | ((reason: unknown) => TResult | PromiseLike) | undefined | null, ): Promise { diff --git a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts index 7995d25424d5..6c209163587a 100644 --- a/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts +++ b/packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts @@ -79,7 +79,7 @@ export default class ReportDispatcher implements Reporter { return this; - function dispatch(method: keyof Reporter, args: any) { + function dispatch(method: keyof Reporter, args: unknown) { if (reporters.length === 0 && fallbackReporter !== null) { reporters.push(fallbackReporter); } diff --git a/packages/jest-jasmine2/src/jasmine/createSpy.ts b/packages/jest-jasmine2/src/jasmine/createSpy.ts index 26adf6dde5f1..9941dfb4485d 100644 --- a/packages/jest-jasmine2/src/jasmine/createSpy.ts +++ b/packages/jest-jasmine2/src/jasmine/createSpy.ts @@ -34,8 +34,8 @@ import type {Spy} from '../types'; import CallTracker, {Context} from './CallTracker'; import SpyStrategy from './SpyStrategy'; -interface Fn extends Record { - (): any; +interface Fn extends Record { + (): unknown; } function createSpy(name: string, originalFn: Fn): Spy { diff --git a/packages/jest-jasmine2/src/queueRunner.ts b/packages/jest-jasmine2/src/queueRunner.ts index b411223d3cce..08087d2569a4 100644 --- a/packages/jest-jasmine2/src/queueRunner.ts +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -17,7 +17,7 @@ export type Options = { onException: (error: Error) => void; queueableFns: Array; setTimeout: Global['setTimeout']; - userContext: any; + userContext: unknown; }; export interface DoneFn { diff --git a/packages/jest-jasmine2/src/treeProcessor.ts b/packages/jest-jasmine2/src/treeProcessor.ts index e46b9abfaca8..6ad17abeabca 100644 --- a/packages/jest-jasmine2/src/treeProcessor.ts +++ b/packages/jest-jasmine2/src/treeProcessor.ts @@ -15,13 +15,13 @@ type Options = { }; export type TreeNode = { - afterAllFns: Array; - beforeAllFns: Array; + afterAllFns: Array; + beforeAllFns: Array; disabled?: boolean; execute: (onComplete: () => void, enabled: boolean) => void; id: string; onException: (error: Error) => void; - sharedUserContext: () => any; + sharedUserContext: () => unknown; children?: Array; } & Pick; @@ -46,13 +46,13 @@ export default function treeProcessor(options: Options): void { } function getNodeWithoutChildrenHandler(node: TreeNode, enabled: boolean) { - return function fn(done: (error?: any) => void = () => {}) { + return function fn(done: (error?: unknown) => void = () => {}) { node.execute(done, enabled); }; } function getNodeWithChildrenHandler(node: TreeNode, enabled: boolean) { - return async function fn(done: (error?: any) => void = () => {}) { + return async function fn(done: (error?: unknown) => void = () => {}) { nodeStart(node); await queueRunnerFactory({ onException: (error: Error) => node.onException(error), diff --git a/packages/jest-jasmine2/src/types.ts b/packages/jest-jasmine2/src/types.ts index d925f61c4ed0..1a4416853b81 100644 --- a/packages/jest-jasmine2/src/types.ts +++ b/packages/jest-jasmine2/src/types.ts @@ -39,9 +39,9 @@ export type AsyncExpectationResult = Promise; export type ExpectationResult = SyncExpectationResult | AsyncExpectationResult; export type RawMatcherFn = ( - expected: any, - actual: any, - options?: any, + expected: unknown, + actual: unknown, + options?: unknown, ) => ExpectationResult; // -------END------- diff --git a/packages/jest-matcher-utils/src/Replaceable.ts b/packages/jest-matcher-utils/src/Replaceable.ts index 07f26d6cd89a..b84194f75d62 100644 --- a/packages/jest-matcher-utils/src/Replaceable.ts +++ b/packages/jest-matcher-utils/src/Replaceable.ts @@ -9,7 +9,11 @@ import getType = require('jest-get-type'); const supportTypes = ['map', 'array', 'object']; -type ReplaceableForEachCallBack = (value: any, key: any, object: any) => void; +type ReplaceableForEachCallBack = ( + value: unknown, + key: unknown, + object: unknown, +) => void; /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ export default class Replaceable { @@ -24,7 +28,7 @@ export default class Replaceable { } } - static isReplaceable(obj1: any, obj2: any): boolean { + static isReplaceable(obj1: unknown, obj2: unknown): boolean { const obj1Type = getType(obj1); const obj2Type = getType(obj2); return obj1Type === obj2Type && supportTypes.includes(obj1Type); diff --git a/packages/jest-matcher-utils/src/__tests__/deepCyclicCopyReplaceable.test.ts b/packages/jest-matcher-utils/src/__tests__/deepCyclicCopyReplaceable.test.ts index 3e647b4de61d..2be86626eb30 100644 --- a/packages/jest-matcher-utils/src/__tests__/deepCyclicCopyReplaceable.test.ts +++ b/packages/jest-matcher-utils/src/__tests__/deepCyclicCopyReplaceable.test.ts @@ -99,7 +99,7 @@ test('Copy Map', () => { }); test('Copy cyclic Map', () => { - const map: Map = new Map([ + const map = new Map([ ['a', 1], ['b', 2], ]); diff --git a/packages/jest-matcher-utils/src/__tests__/index.test.ts b/packages/jest-matcher-utils/src/__tests__/index.test.ts index f772aa6a8017..fbba12527ebc 100644 --- a/packages/jest-matcher-utils/src/__tests__/index.test.ts +++ b/packages/jest-matcher-utils/src/__tests__/index.test.ts @@ -20,7 +20,6 @@ import { stringify, } from '../'; -/* global BigInt */ const isBigIntDefined = typeof BigInt === 'function'; expect.addSnapshotSerializer(alignedAnsiStyleSerializer); diff --git a/packages/jest-matcher-utils/src/__tests__/printDiffOrStringify.test.ts b/packages/jest-matcher-utils/src/__tests__/printDiffOrStringify.test.ts index 874d38ec6068..109432a95825 100644 --- a/packages/jest-matcher-utils/src/__tests__/printDiffOrStringify.test.ts +++ b/packages/jest-matcher-utils/src/__tests__/printDiffOrStringify.test.ts @@ -149,7 +149,7 @@ describe('printDiffOrStringify', () => { test('custom asymmetricMatcher', () => { expect.extend({ - equal5(received: any) { + equal5(received: unknown) { if (received === 5) return { message: () => `expected ${received} not to be 5`, @@ -194,24 +194,24 @@ describe('printDiffOrStringify', () => { }); test('array', () => { - const expected: Array = [1, expect.any(Number), 3]; - const received: Array = [1, 2, 2]; + const expected: Array = [1, expect.any(Number), 3]; + const received: Array = [1, 2, 2]; expect(testDiffOrStringify(expected, received)).toMatchSnapshot(); }); test('object in array', () => { - const expected: Array = [1, {a: 1, b: expect.any(Number)}, 3]; - const received: Array = [1, {a: 1, b: 2}, 2]; + const expected: Array = [1, {a: 1, b: expect.any(Number)}, 3]; + const received: Array = [1, {a: 1, b: 2}, 2]; expect(testDiffOrStringify(expected, received)).toMatchSnapshot(); }); test('map', () => { - const expected: Map = new Map([ + const expected: Map = new Map([ ['a', 1], ['b', expect.any(Number)], ['c', 3], ]); - const received: Map = new Map([ + const received: Map = new Map([ ['a', 1], ['b', 2], ['c', 2], @@ -234,7 +234,7 @@ describe('printDiffOrStringify', () => { }); test('transitive circular', () => { - const expected: any = { + const expected: unknown = { a: 3, }; expected.nested = {b: expect.any(Number), parent: expected}; @@ -246,21 +246,21 @@ describe('printDiffOrStringify', () => { }); test('circular array', () => { - const expected: Array = [1, expect.any(Number), 3]; + const expected: Array = [1, expect.any(Number), 3]; expected.push(expected); - const received: Array = [1, 2, 2]; + const received: Array = [1, 2, 2]; received.push(received); expect(testDiffOrStringify(expected, received)).toMatchSnapshot(); }); test('circular map', () => { - const expected: Map = new Map([ + const expected: Map = new Map([ ['a', 1], ['b', expect.any(Number)], ['c', 3], ]); expected.set('circular', expected); - const received: Map = new Map([ + const received: Map = new Map([ ['a', 1], ['b', 2], ['c', 2], diff --git a/packages/jest-matcher-utils/src/deepCyclicCopyReplaceable.ts b/packages/jest-matcher-utils/src/deepCyclicCopyReplaceable.ts index 2a22bcfddaf4..8928927b8d2d 100644 --- a/packages/jest-matcher-utils/src/deepCyclicCopyReplaceable.ts +++ b/packages/jest-matcher-utils/src/deepCyclicCopyReplaceable.ts @@ -28,7 +28,8 @@ const builtInObject = [ const isBuiltInObject = (object: any) => builtInObject.includes(object.constructor); -const isMap = (value: any): value is Map => value.constructor === Map; +const isMap = (value: any): value is Map => + value.constructor === Map; export default function deepCyclicCopyReplaceable( value: T, @@ -51,7 +52,7 @@ export default function deepCyclicCopyReplaceable( } } -function deepCyclicCopyObject(object: T, cycles: WeakMap): T { +function deepCyclicCopyObject(object: T, cycles: WeakMap): T { const newObject = Object.create(Object.getPrototypeOf(object)); const descriptors: { [x: string]: PropertyDescriptor; @@ -88,7 +89,10 @@ function deepCyclicCopyObject(object: T, cycles: WeakMap): T { return Object.defineProperties(newObject, newDescriptors); } -function deepCyclicCopyArray(array: Array, cycles: WeakMap): T { +function deepCyclicCopyArray( + array: Array, + cycles: WeakMap, +): T { const newArray = new (Object.getPrototypeOf(array).constructor)(array.length); const length = array.length; @@ -102,8 +106,8 @@ function deepCyclicCopyArray(array: Array, cycles: WeakMap): T { } function deepCyclicCopyMap( - map: Map, - cycles: WeakMap, + map: Map, + cycles: WeakMap, ): T { const newMap = new Map(); diff --git a/packages/jest-matcher-utils/src/index.ts b/packages/jest-matcher-utils/src/index.ts index 1f2c80514c56..3013c77ebc53 100644 --- a/packages/jest-matcher-utils/src/index.ts +++ b/packages/jest-matcher-utils/src/index.ts @@ -410,8 +410,8 @@ const shouldPrintDiff = (actual: unknown, expected: unknown) => { function replaceMatchedToAsymmetricMatcher( replacedExpected: unknown, replacedReceived: unknown, - expectedCycles: Array, - receivedCycles: Array, + expectedCycles: Array, + receivedCycles: Array, ) { if (!Replaceable.isReplaceable(replacedExpected, replacedReceived)) { return {replacedExpected, replacedReceived}; diff --git a/packages/jest-repl/src/cli/repl.ts b/packages/jest-repl/src/cli/repl.ts index 0b49eb045d39..831b2323489a 100644 --- a/packages/jest-repl/src/cli/repl.ts +++ b/packages/jest-repl/src/cli/repl.ts @@ -18,9 +18,9 @@ let transformer: Transformer; const evalCommand: repl.REPLEval = ( cmd: string, - _context: any, + _context: unknown, _filename: string, - callback: (e: Error | null, result?: any) => void, + callback: (e: Error | null, result?: unknown) => void, ) => { let result; try { diff --git a/packages/jest-reporters/src/__tests__/notify_reporter.test.ts b/packages/jest-reporters/src/__tests__/notify_reporter.test.ts index cbaaac084810..3e0e112a48d0 100644 --- a/packages/jest-reporters/src/__tests__/notify_reporter.test.ts +++ b/packages/jest-reporters/src/__tests__/notify_reporter.test.ts @@ -224,7 +224,7 @@ describe('node-notifier is an optional dependency', () => { test('without node-notifier uses mock function that throws an error', () => { jest.doMock('node-notifier', () => { - const error: any = new Resolver.ModuleNotFoundError( + const error: unknown = new Resolver.ModuleNotFoundError( "Cannot find module 'node-notifier'", ); throw error; diff --git a/packages/jest-reporters/src/default_reporter.ts b/packages/jest-reporters/src/default_reporter.ts index e39238841c58..7c7f496856f8 100644 --- a/packages/jest-reporters/src/default_reporter.ts +++ b/packages/jest-reporters/src/default_reporter.ts @@ -21,7 +21,7 @@ import Status from './Status'; import getResultHeader from './get_result_header'; import getSnapshotStatus from './get_snapshot_status'; -type write = (chunk: string, enc?: any, cb?: () => void) => boolean; +type write = NodeJS.WriteStream['write']; type FlushBufferedOutput = () => void; const TITLE_BULLET = chalk.bold('\u25cf '); diff --git a/packages/jest-reporters/src/notify_reporter.ts b/packages/jest-reporters/src/notify_reporter.ts index f6186f078ca9..f6f0bd367924 100644 --- a/packages/jest-reporters/src/notify_reporter.ts +++ b/packages/jest-reporters/src/notify_reporter.ts @@ -20,13 +20,13 @@ const icon = path.resolve(__dirname, '../assets/jest_logo.png'); export default class NotifyReporter extends BaseReporter { private _notifier = loadNotifier(); - private _startRun: (globalConfig: Config.GlobalConfig) => any; + private _startRun: (globalConfig: Config.GlobalConfig) => unknown; private _globalConfig: Config.GlobalConfig; private _context: TestSchedulerContext; constructor( globalConfig: Config.GlobalConfig, - startRun: (globalConfig: Config.GlobalConfig) => any, + startRun: (globalConfig: Config.GlobalConfig) => unknown, context: TestSchedulerContext, ) { super(); @@ -117,8 +117,7 @@ export default class NotifyReporter extends BaseReporter { message, timeout: false, title, - // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/42303 - } as any, + }, (err, _, metadata) => { if (err || !metadata) { return; diff --git a/packages/jest-reporters/src/types.ts b/packages/jest-reporters/src/types.ts index 62dede0afed8..45dc7c5c00f6 100644 --- a/packages/jest-reporters/src/types.ts +++ b/packages/jest-reporters/src/types.ts @@ -50,8 +50,11 @@ export type OnTestStart = (test: Test) => Promise; export type OnTestFailure = ( test: Test, error: SerializableError, -) => Promise; -export type OnTestSuccess = (test: Test, result: TestResult) => Promise; +) => Promise; +export type OnTestSuccess = ( + test: Test, + result: TestResult, +) => Promise; export interface Reporter { readonly onTestResult?: ( 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 c30c1a7fd6a1..d32526f3fd81 100644 --- a/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.ts +++ b/packages/jest-resolve-dependencies/src/__tests__/dependency_resolver.test.ts @@ -11,13 +11,12 @@ import Resolver = require('jest-resolve'); import type {Config} from '@jest/types'; import {buildSnapshotResolver} from 'jest-snapshot'; import {makeProjectConfig} from '../../../../TestUtils'; - import DependencyResolver from '../index'; const maxWorkers = 1; let dependencyResolver: DependencyResolver; let runtimeContextResolver: Resolver; -let Runtime; +let Runtime: typeof import('jest-runtime'); let config: Config.ProjectConfig; const cases: Record = { fancyCondition: jest.fn(path => path.length > 10), @@ -36,7 +35,7 @@ beforeEach(() => { roots: ['./packages/jest-resolve-dependencies'], }); return Runtime.createContext(config, {maxWorkers, watchman: false}).then( - (runtimeContext: any) => { + runtimeContext => { runtimeContextResolver = runtimeContext.resolver; dependencyResolver = new DependencyResolver( runtimeContext.resolver, diff --git a/packages/jest-runtime/src/__tests__/runtime_require_resolve.test.ts b/packages/jest-runtime/src/__tests__/runtime_require_resolve.test.ts index d7ce25458f44..77e35813eceb 100644 --- a/packages/jest-runtime/src/__tests__/runtime_require_resolve.test.ts +++ b/packages/jest-runtime/src/__tests__/runtime_require_resolve.test.ts @@ -47,7 +47,7 @@ describe('Runtime require.resolve', () => { describe('with the OUTSIDE_JEST_VM_RESOLVE_OPTION', () => { it('forwards to the real Node require in an internal context', async () => { const runtime = await createRuntime(__filename); - const module = runtime.requireInternalModule( + const module = runtime.requireInternalModule( runtime.__mockRootPath, './resolve_and_require_outside.js', ); @@ -58,7 +58,7 @@ describe('Runtime require.resolve', () => { it('ignores the option in an external context', async () => { const runtime = await createRuntime(__filename); - const module = runtime.requireModule( + const module = runtime.requireModule( runtime.__mockRootPath, './resolve_and_require_outside.js', ); @@ -72,7 +72,7 @@ describe('Runtime require.resolve', () => { it('does not understand a self-constructed outsideJestVmPath in an external context', async () => { const runtime = await createRuntime(__filename); expect(() => - runtime.requireModule( + runtime.requireModule( runtime.__mockRootPath, createOutsideJestVmPath( require.resolve('./test_root/create_require_module.js'), diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index 52b11bcad44e..e81d6020ec72 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -158,8 +158,8 @@ class Runtime { string, jestMock.MockFunctionMetadata> >; - private _mockRegistry: Map; - private _isolatedMockRegistry: Map | null; + private _mockRegistry: Map; + private _isolatedMockRegistry: Map | null; private _moduleMocker: typeof jestMock; private _isolatedModuleRegistry: ModuleRegistry | null; private _moduleRegistry: ModuleRegistry; @@ -1049,7 +1049,7 @@ class Runtime { this.jestObjectCaches.set(filename, jestObject); - const lastArgs: [Jest | undefined, ...Array] = [ + const lastArgs: [Jest | undefined, ...Array] = [ this._config.injectGlobals ? jestObject : undefined, // jest object this._config.extraGlobals.map(globalVariable => { if (this._environment.global[globalVariable]) { @@ -1506,7 +1506,7 @@ class Runtime { }; const jestObject: Jest = { - addMatchers: (matchers: Record) => + addMatchers: (matchers: Record) => this._environment.global.jasmine.addMatchers(matchers), advanceTimersByTime: (msToRun: number) => _getFakeTimers().advanceTimersByTime(msToRun), @@ -1700,7 +1700,7 @@ class Runtime { beforeAll: this._environment.global.beforeAll, beforeEach: this._environment.global.beforeEach, describe: this._environment.global.describe, - expect: this._environment.global.expect as any, + expect: this._environment.global.expect as unknown, fdescribe: this._environment.global.fdescribe, fit: this._environment.global.fit, it: this._environment.global.it, diff --git a/packages/jest-serializer/src/index.ts b/packages/jest-serializer/src/index.ts index 8f6bd7a9913d..f4dd28e11152 100644 --- a/packages/jest-serializer/src/index.ts +++ b/packages/jest-serializer/src/index.ts @@ -19,7 +19,7 @@ type Path = string; // In memory functions. -export function deserialize(buffer: Buffer): any { +export function deserialize(buffer: Buffer): unknown { return v8Deserialize(buffer); } @@ -29,7 +29,7 @@ export function serialize(content: unknown): Buffer { // Synchronous filesystem functions. -export function readFileSync(filePath: Path): any { +export function readFileSync(filePath: Path): unknown { return v8Deserialize(fs.readFileSync(filePath)); } diff --git a/packages/jest-snapshot/src/__tests__/matcher.test.ts b/packages/jest-snapshot/src/__tests__/matcher.test.ts index 5bbfe1226577..a8e4ee90a526 100644 --- a/packages/jest-snapshot/src/__tests__/matcher.test.ts +++ b/packages/jest-snapshot/src/__tests__/matcher.test.ts @@ -14,7 +14,7 @@ it(`matcher returns matcher name, expected and actual values`, () => { const expected = 'b'; const matcher = toMatchSnapshot.bind({ snapshotState: { - match: (_testName: string, _received: any) => ({actual, expected}), + match: (_testName: string, _received: unknown) => ({actual, expected}), }, }); diff --git a/packages/jest-snapshot/src/__tests__/printSnapshot.test.ts b/packages/jest-snapshot/src/__tests__/printSnapshot.test.ts index be2c9a431678..85bd10a85786 100644 --- a/packages/jest-snapshot/src/__tests__/printSnapshot.test.ts +++ b/packages/jest-snapshot/src/__tests__/printSnapshot.test.ts @@ -128,7 +128,7 @@ expect.addSnapshotSerializer({ serialize(val: string): string { return convertAnsi(val); }, - test(val: any): val is string { + test(val: unknown): val is string { return typeof val === 'string'; }, }); diff --git a/packages/jest-snapshot/src/printSnapshot.ts b/packages/jest-snapshot/src/printSnapshot.ts index 3a17abce95d6..ddd5814b0b14 100644 --- a/packages/jest-snapshot/src/printSnapshot.ts +++ b/packages/jest-snapshot/src/printSnapshot.ts @@ -168,7 +168,7 @@ const joinDiffs = ( '', ); -const isLineDiffable = (received: any): boolean => { +const isLineDiffable = (received: unknown): boolean => { const receivedType = getType(received); if (getType.isPrimitive(received)) { diff --git a/packages/jest-snapshot/src/types.ts b/packages/jest-snapshot/src/types.ts index 8dbd91c9c31a..084379dab721 100644 --- a/packages/jest-snapshot/src/types.ts +++ b/packages/jest-snapshot/src/types.ts @@ -21,7 +21,7 @@ export type MatchSnapshotConfig = { isInline: boolean; matcherName: string; properties?: object; - received: any; + received: unknown; }; export type SnapshotData = Record; diff --git a/packages/jest-source-map/src/__tests__/getCallsite.test.ts b/packages/jest-source-map/src/__tests__/getCallsite.test.ts index fd36f705fb83..ddb7903e0777 100644 --- a/packages/jest-source-map/src/__tests__/getCallsite.test.ts +++ b/packages/jest-source-map/src/__tests__/getCallsite.test.ts @@ -46,7 +46,7 @@ describe('getCallsite', () => { const sourceMapLine = 2; SourceMap.SourceMapConsumer = class { - originalPositionFor(params: Record) { + originalPositionFor(params: Record) { expect(params).toMatchObject({ column: expect.any(Number), line: expect.any(Number), diff --git a/packages/jest-test-result/src/types.ts b/packages/jest-test-result/src/types.ts index 24f351feccf4..25bcf43e892d 100644 --- a/packages/jest-test-result/src/types.ts +++ b/packages/jest-test-result/src/types.ts @@ -20,13 +20,13 @@ export type SerializableError = TestResult.SerializableError; export type FailedAssertion = { matcherName?: string; message?: string; - actual?: any; + actual?: unknown; pass?: boolean; passed?: boolean; - expected?: any; + expected?: unknown; isNot?: boolean; stack?: string; - error?: any; + error?: unknown; }; export type AssertionLocation = { @@ -125,7 +125,7 @@ export type FormattedTestResult = { status: 'failed' | 'passed'; startTime: number; endTime: number; - coverage: any; + coverage: unknown; assertionResults: Array; }; @@ -147,12 +147,12 @@ export type FormattedTestResults = { wasInterrupted: boolean; }; -export type CodeCoverageReporter = any; +export type CodeCoverageReporter = unknown; export type CodeCoverageFormatter = ( coverage: CoverageMapData | null | undefined, reporter: CodeCoverageReporter, -) => Record | null | undefined; +) => Record | null | undefined; export type UncheckedSnapshot = { filePath: string; diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index c9500cc31bdf..7fd85863146d 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -52,7 +52,7 @@ const projectCaches = new Map(); const CACHE_VERSION = '1'; async function waitForPromiseWithCleanup( - promise: Promise, + promise: Promise, cleanup: () => void, ) { try { diff --git a/packages/jest-types/src/Circus.ts b/packages/jest-types/src/Circus.ts index 9868b5268122..5dec97bda397 100644 --- a/packages/jest-types/src/Circus.ts +++ b/packages/jest-types/src/Circus.ts @@ -20,7 +20,7 @@ export type HookFn = Global.HookFn; export type AsyncFn = TestFn | HookFn; export type SharedHookType = 'afterAll' | 'beforeAll'; export type HookType = SharedHookType | 'afterEach' | 'beforeEach'; -export type TestContext = Record; +export type TestContext = Record; export type Exception = any; // Since in JS anything can be thrown as an error. export type FormattedError = string; // String representation of error. export type Hook = { @@ -186,7 +186,7 @@ export type TestResults = Array; export type GlobalErrorHandlers = { uncaughtException: Array<(exception: Exception) => void>; unhandledRejection: Array< - (exception: Exception, promise: Promise) => void + (exception: Exception, promise: Promise) => void >; }; diff --git a/packages/jest-types/src/Config.ts b/packages/jest-types/src/Config.ts index bfae5927dd3a..c492b08740df 100644 --- a/packages/jest-types/src/Config.ts +++ b/packages/jest-types/src/Config.ts @@ -83,7 +83,7 @@ export type DefaultOptions = { slowTestThreshold: number; snapshotSerializers: Array; testEnvironment: string; - testEnvironmentOptions: Record; + testEnvironmentOptions: Record; testFailureExitCode: string | number; testLocationInResults: boolean; testMatch: Array; @@ -193,7 +193,7 @@ export type InitialOptions = Partial<{ snapshotSerializers: Array; errorOnDeprecated: boolean; testEnvironment: string; - testEnvironmentOptions: Record; + testEnvironmentOptions: Record; testFailureExitCode: string | number; testLocationInResults: boolean; testMatch: Array; @@ -219,7 +219,7 @@ export type InitialOptions = Partial<{ watch: boolean; watchAll: boolean; watchman: boolean; - watchPlugins: Array]>; + watchPlugins: Array]>; }>; export type SnapshotUpdateState = 'all' | 'new' | 'none'; @@ -308,7 +308,7 @@ export type GlobalConfig = { watchman: boolean; watchPlugins?: Array<{ path: string; - config: Record; + config: Record; }> | null; }; @@ -355,7 +355,7 @@ export type ProjectConfig = { snapshotResolver?: Path; snapshotSerializers: Array; testEnvironment: string; - testEnvironmentOptions: Record; + testEnvironmentOptions: Record; testMatch: Array; testLocationInResults: boolean; testPathIgnorePatterns: Array; diff --git a/packages/jest-util/src/__tests__/installCommonGlobals.test.ts b/packages/jest-util/src/__tests__/installCommonGlobals.test.ts index d3f57912a483..6bde7264523e 100644 --- a/packages/jest-util/src/__tests__/installCommonGlobals.test.ts +++ b/packages/jest-util/src/__tests__/installCommonGlobals.test.ts @@ -7,7 +7,7 @@ import {createContext, runInContext} from 'vm'; -let installCommonGlobals: any; +let installCommonGlobals: typeof import('../installCommonGlobals').default; let fake: jest.Mock; function getGlobal(): NodeJS.Global { diff --git a/packages/jest-util/src/createProcessObject.ts b/packages/jest-util/src/createProcessObject.ts index 1c391acb8136..569977a339c1 100644 --- a/packages/jest-util/src/createProcessObject.ts +++ b/packages/jest-util/src/createProcessObject.ts @@ -9,7 +9,7 @@ import deepCyclicCopy from './deepCyclicCopy'; const BLACKLIST = new Set(['env', 'mainModule', '_events']); const isWin32 = process.platform === 'win32'; -const proto: Record = Object.getPrototypeOf(process.env); +const proto: Record = Object.getPrototypeOf(process.env); // The "process.env" object has a bunch of particularities: first, it does not // directly extend from Object; second, it converts any assigned value to a @@ -20,7 +20,7 @@ function createProcessEnv(): NodeJS.ProcessEnv { const real = Object.create(proto); const lookup: typeof process.env = {}; - function deletePropertyWin32(_target: any, key: any) { + function deletePropertyWin32(_target: unknown, key: unknown) { for (const name in real) { if (real.hasOwnProperty(name)) { if (typeof key === 'string') { @@ -40,18 +40,18 @@ function createProcessEnv(): NodeJS.ProcessEnv { return true; } - function deleteProperty(_target: any, key: any) { + function deleteProperty(_target: unknown, key: any) { delete real[key]; delete lookup[key]; return true; } - function getProperty(_target: any, key: any) { + function getProperty(_target: unknown, key: any) { return real[key]; } - function getPropertyWin32(_target: any, key: any) { + function getPropertyWin32(_target: unknown, key: any) { if (typeof key === 'string') { return lookup[key in proto ? key : key.toLowerCase()]; } else { diff --git a/packages/jest-validate/src/condition.ts b/packages/jest-validate/src/condition.ts index 9ae9be24416c..8302f865f10d 100644 --- a/packages/jest-validate/src/condition.ts +++ b/packages/jest-validate/src/condition.ts @@ -39,7 +39,7 @@ export function validationCondition( return getValues(validOption).some(e => validationConditionSingle(option, e)); } -export function multipleValidOptions>( +export function multipleValidOptions>( ...args: T ): T[number] { const options = [...args]; diff --git a/packages/jest-validate/src/deprecated.ts b/packages/jest-validate/src/deprecated.ts index eb24719c6c7c..d6776bc7686d 100644 --- a/packages/jest-validate/src/deprecated.ts +++ b/packages/jest-validate/src/deprecated.ts @@ -17,7 +17,7 @@ const deprecationMessage = (message: string, options: ValidationOptions) => { }; export const deprecationWarning = ( - config: Record, + config: Record, option: string, deprecatedOptions: DeprecatedOptions, options: ValidationOptions, diff --git a/packages/jest-validate/src/errors.ts b/packages/jest-validate/src/errors.ts index f70d01cf79c7..ebd6c1d6a3b3 100644 --- a/packages/jest-validate/src/errors.ts +++ b/packages/jest-validate/src/errors.ts @@ -39,7 +39,7 @@ ${formatExamples(option, conditions)}`; throw new ValidationError(name, message, comment); }; -function formatExamples(option: string, examples: Array) { +function formatExamples(option: string, examples: Array) { return examples.map( e => ` { ${chalk.bold(`"${option}"`)}: ${chalk.bold(formatPrettyObject(e))} diff --git a/packages/jest-validate/src/types.ts b/packages/jest-validate/src/types.ts index b0e72f7dcc4b..a87171f78cf8 100644 --- a/packages/jest-validate/src/types.ts +++ b/packages/jest-validate/src/types.ts @@ -11,15 +11,15 @@ type Title = { warning?: string; }; -export type DeprecatedOptionFunc = (arg: Record) => string; +export type DeprecatedOptionFunc = (arg: Record) => string; export type DeprecatedOptions = Record; export type ValidationOptions = { comment?: string; - condition?: (option: any, validOption: any) => boolean; + condition?: (option: unknown, validOption: unknown) => boolean; deprecate?: ( - config: Record, + config: Record, option: string, deprecatedOptions: DeprecatedOptions, options: ValidationOptions, @@ -27,18 +27,18 @@ export type ValidationOptions = { deprecatedConfig?: DeprecatedOptions; error?: ( option: string, - received: any, - defaultValue: any, + received: unknown, + defaultValue: unknown, options: ValidationOptions, path?: Array, ) => void; - exampleConfig: Record; + exampleConfig: Record; recursive?: boolean; recursiveBlacklist?: Array; title?: Title; unknown?: ( - config: Record, - exampleConfig: Record, + config: Record, + exampleConfig: Record, option: string, options: ValidationOptions, path?: Array, diff --git a/packages/jest-validate/src/validate.ts b/packages/jest-validate/src/validate.ts index 4e63da9eaed9..d3a0002812ee 100644 --- a/packages/jest-validate/src/validate.ts +++ b/packages/jest-validate/src/validate.ts @@ -92,11 +92,11 @@ const _validate = ( }; const allowsMultipleTypes = (key: string): boolean => key === 'maxWorkers'; -const isOfTypeStringOrNumber = (value: any): boolean => +const isOfTypeStringOrNumber = (value: unknown): boolean => typeof value === 'number' || typeof value === 'string'; const validate = ( - config: Record, + config: Record, options: ValidationOptions, ): {hasDeprecationWarnings: boolean; isValid: boolean} => { hasDeprecationWarnings = false; diff --git a/packages/jest-validate/src/warnings.ts b/packages/jest-validate/src/warnings.ts index 125f21551d87..4a661d58c037 100644 --- a/packages/jest-validate/src/warnings.ts +++ b/packages/jest-validate/src/warnings.ts @@ -15,8 +15,8 @@ import { } from './utils'; export const unknownOptionWarning = ( - config: Record, - exampleConfig: Record, + config: Record, + exampleConfig: Record, option: string, options: ValidationOptions, path?: Array, diff --git a/packages/jest-worker/src/index.ts b/packages/jest-worker/src/index.ts index 6ae1b96b0d17..af430beac0c2 100644 --- a/packages/jest-worker/src/index.ts +++ b/packages/jest-worker/src/index.ts @@ -27,7 +27,7 @@ function getExposedMethods( // If no methods list is given, try getting it by auto-requiring the module. if (!exposedMethods) { - const module: Function | Record = require(workerPath); + const module: Function | Record = require(workerPath); exposedMethods = Object.keys(module).filter( // @ts-expect-error: no index @@ -126,7 +126,7 @@ export default class JestWorker { private _callFunctionWithArgs( method: string, ...args: Array - ): Promise { + ): 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/workers/processChild.ts b/packages/jest-worker/src/workers/processChild.ts index 96a298cf33e9..64d29e19e132 100644 --- a/packages/jest-worker/src/workers/processChild.ts +++ b/packages/jest-worker/src/workers/processChild.ts @@ -34,7 +34,7 @@ let initialized = false; * If an invalid message is detected, the child will exit (by throwing) with a * non-zero exit code. */ -const messageListener = (request: any) => { +const messageListener: NodeJS.MessageListener = request => { switch (request[0]) { case CHILD_MESSAGE_INITIALIZE: const init: ChildMessageInitialize = request; @@ -59,7 +59,7 @@ const messageListener = (request: any) => { }; process.on('message', messageListener); -function reportSuccess(result: any) { +function reportSuccess(result: unknown) { if (!process || !process.send) { throw new Error('Child can only be used on a forked process'); } @@ -110,7 +110,7 @@ function exitProcess(): void { process.removeListener('message', messageListener); } -function execMethod(method: string, args: Array): void { +function execMethod(method: string, args: Array): void { const main = require(file!); let fn: (...args: Array) => unknown; @@ -136,8 +136,13 @@ function execMethod(method: string, args: Array): void { execFunction(main.setup, main, setupArgs, execHelper, reportInitializeError); } +const isPromise = (obj: any): obj is PromiseLike => + !!obj && + (typeof obj === 'object' || typeof obj === 'function') && + typeof obj.then === 'function'; + function execFunction( - fn: (...args: Array) => any | Promise, + fn: (...args: Array) => unknown | Promise, ctx: unknown, args: Array, onResult: (result: unknown) => void, @@ -153,7 +158,7 @@ function execFunction( return; } - if (result && typeof result.then === 'function') { + if (isPromise(result)) { result.then(onResult, onError); } else { onResult(result); diff --git a/packages/jest-worker/src/workers/threadChild.ts b/packages/jest-worker/src/workers/threadChild.ts index fc9105ce99ce..52a1f1c239e1 100644 --- a/packages/jest-worker/src/workers/threadChild.ts +++ b/packages/jest-worker/src/workers/threadChild.ts @@ -61,7 +61,7 @@ const messageListener = (request: any) => { }; parentPort!.on('message', messageListener); -function reportSuccess(result: any) { +function reportSuccess(result: unknown) { if (isMainThread) { throw new Error('Child can only be used on a forked process'); } @@ -112,7 +112,7 @@ function exitProcess(): void { parentPort!.removeListener('message', messageListener); } -function execMethod(method: string, args: Array): void { +function execMethod(method: string, args: Array): void { const main = require(file!); let fn: (...args: Array) => unknown; @@ -138,8 +138,13 @@ function execMethod(method: string, args: Array): void { execFunction(main.setup, main, setupArgs, execHelper, reportInitializeError); } +const isPromise = (obj: any): obj is PromiseLike => + !!obj && + (typeof obj === 'object' || typeof obj === 'function') && + typeof obj.then === 'function'; + function execFunction( - fn: (...args: Array) => any, + fn: (...args: Array) => unknown, ctx: unknown, args: Array, onResult: (result: unknown) => void, @@ -155,7 +160,7 @@ function execFunction( return; } - if (result && typeof result.then === 'function') { + if (isPromise(result)) { result.then(onResult, onError); } else { onResult(result); diff --git a/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts b/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts index a9766c401faa..e31c763efe7b 100644 --- a/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts +++ b/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts @@ -12,7 +12,7 @@ import prettyFormat from '../'; const {AsymmetricMatcher} = prettyFormat.plugins; let options: OptionsReceived; -function fnNameFor(func: (...any: Array) => any) { +function fnNameFor(func: (...any: Array) => unknown) { if (func.name) { return func.name; } diff --git a/packages/pretty-format/src/__tests__/Immutable.test.ts b/packages/pretty-format/src/__tests__/Immutable.test.ts index 6d124ebcf833..651c8da8bd41 100644 --- a/packages/pretty-format/src/__tests__/Immutable.test.ts +++ b/packages/pretty-format/src/__tests__/Immutable.test.ts @@ -505,7 +505,7 @@ describe('Immutable.OrderedMap', () => { }); it('supports non-string keys', () => { - const val = Immutable.OrderedMap([ + const val = Immutable.OrderedMap([ [false, 'boolean'], ['false', 'string'], [0, 'number'], diff --git a/packages/pretty-format/src/__tests__/ReactElement.test.ts b/packages/pretty-format/src/__tests__/ReactElement.test.ts index e37f72a19936..8946c4e3027a 100644 --- a/packages/pretty-format/src/__tests__/ReactElement.test.ts +++ b/packages/pretty-format/src/__tests__/ReactElement.test.ts @@ -15,7 +15,7 @@ setPrettyPrint([ReactElement]); describe('ReactElement Plugin', () => { let forwardRefComponent: { - (_props: any, _ref: any): any; + (_props: unknown, _ref: unknown): unknown; displayName?: string; }; diff --git a/packages/pretty-format/src/__tests__/prettyFormat.test.ts b/packages/pretty-format/src/__tests__/prettyFormat.test.ts index ce6652f19909..0189abdfa742 100644 --- a/packages/pretty-format/src/__tests__/prettyFormat.test.ts +++ b/packages/pretty-format/src/__tests__/prettyFormat.test.ts @@ -156,7 +156,7 @@ describe('prettyFormat()', () => { }); it('prints a map with non-string keys', () => { - const val = new Map([ + const val = new Map([ [false, 'boolean'], ['false', 'string'], [0, 'number'], @@ -280,7 +280,7 @@ describe('prettyFormat()', () => { }); it('prints an object without non-enumerable properties which have string key', () => { - const val: any = { + const val: unknown = { enumerable: true, }; const key = 'non-enumerable'; @@ -292,7 +292,7 @@ describe('prettyFormat()', () => { }); it('prints an object without non-enumerable properties which have symbol key', () => { - const val: any = { + const val: unknown = { enumerable: true, }; const key = Symbol('non-enumerable'); @@ -585,7 +585,7 @@ describe('prettyFormat()', () => { const options = { plugins: [ { - print(val: any) { + print(val: unknown) { return val; }, test() { @@ -668,10 +668,10 @@ describe('prettyFormat()', () => { prettyFormat(val, { plugins: [ { - print(val, print) { - return val.map((item: any) => print(item)).join(' - '); + print(val: Array, print: any) { + return val.map(item => print(item)).join(' - '); }, - test(val) { + test(val: unknown) { return Array.isArray(val); }, }, diff --git a/packages/pretty-format/src/__tests__/react.test.tsx b/packages/pretty-format/src/__tests__/react.test.tsx index 6cda12c16715..c79cef239e77 100644 --- a/packages/pretty-format/src/__tests__/react.test.tsx +++ b/packages/pretty-format/src/__tests__/react.test.tsx @@ -17,17 +17,17 @@ const suspenseSymbol = Symbol.for('react.suspense'); const testSymbol = Symbol.for('react.test.json'); const {ReactElement, ReactTestComponent} = prettyFormat.plugins; -const formatElement = (element: any, options?: OptionsReceived) => +const formatElement = (element: unknown, options?: OptionsReceived) => prettyFormat(element, {plugins: [ReactElement], ...options}); -const formatTestObject = (object: any, options?: OptionsReceived) => +const formatTestObject = (object: unknown, options?: OptionsReceived) => prettyFormat(object, { plugins: [ReactTestComponent, ReactElement], ...options, }); function assertPrintedJSX( - val: any, + val: unknown, expected: string, options?: OptionsReceived, ) { @@ -114,7 +114,7 @@ test('supports props with numbers', () => { test('supports a single element with a function prop', () => { assertPrintedJSX( - React.createElement<{onclick: any}>('Mouse', { + React.createElement<{onclick: unknown}>('Mouse', { onclick: function onclick() {}, }), '', @@ -141,7 +141,7 @@ test('supports an element with and object prop and children', () => { test('supports an element with complex props and mixed children', () => { assertPrintedJSX( - React.createElement<{customProp: any; onclick: any}>( + React.createElement<{customProp: unknown; onclick: unknown}>( 'Mouse', {customProp: {one: '1', two: 2}, onclick: function onclick() {}}, 'HELLO', @@ -167,11 +167,11 @@ test('escapes children properly', () => { test('supports everything all together', () => { assertPrintedJSX( - React.createElement<{customProp: any; onclick: any}>( + React.createElement<{customProp: unknown; onclick: unknown}>( 'Mouse', {customProp: {one: '1', two: 2}, onclick: function onclick() {}}, 'HELLO', - React.createElement<{customProp: any; onclick: any}>( + React.createElement<{customProp: unknown; onclick: unknown}>( 'Mouse', {customProp: {one: '1', two: 2}, onclick: function onclick() {}}, 'HELLO', @@ -266,7 +266,7 @@ test('supports a single element with custom React elements with props (using ano }); test('supports a single element with custom React elements with a child', () => { - function Cat(props: any) { + function Cat(props: unknown) { return React.createElement('div', props); } assertPrintedJSX( @@ -577,7 +577,7 @@ describe('maxDepth option', () => { test('min option', () => { assertPrintedJSX( - React.createElement<{customProp: any; onclick: any}>( + React.createElement<{customProp: unknown; onclick: unknown}>( 'Mouse', {customProp: {one: '1', two: 2}, onclick: function onclick() {}}, 'HELLO', diff --git a/packages/pretty-format/src/__tests__/setPrettyPrint.ts b/packages/pretty-format/src/__tests__/setPrettyPrint.ts index 58b2d55ce499..c7d2e65f28b5 100644 --- a/packages/pretty-format/src/__tests__/setPrettyPrint.ts +++ b/packages/pretty-format/src/__tests__/setPrettyPrint.ts @@ -14,14 +14,18 @@ declare global { namespace jest { // eslint-disable-next-line @typescript-eslint/no-unused-vars interface Matchers { - toPrettyPrintTo(expected: any, options?: OptionsReceived): R; + toPrettyPrintTo(expected: unknown, options?: OptionsReceived): R; } } } const setPrettyPrint = (plugins: Plugins) => { expect.extend({ - toPrettyPrintTo(received: any, expected: any, options?: OptionsReceived) { + toPrettyPrintTo( + received: unknown, + expected: unknown, + options?: OptionsReceived, + ) { const prettyFormatted = prettyFormat(received, {plugins, ...options}); const pass = prettyFormatted === expected; diff --git a/packages/pretty-format/src/collections.ts b/packages/pretty-format/src/collections.ts index e97c3ceb6a13..7876309e702b 100644 --- a/packages/pretty-format/src/collections.ts +++ b/packages/pretty-format/src/collections.ts @@ -8,7 +8,7 @@ import type {Config, Printer, Refs} from './types'; -const getKeysOfEnumerableProperties = (object: Record) => { +const getKeysOfEnumerableProperties = (object: Record) => { const keys: Array = Object.keys(object).sort(); if (Object.getOwnPropertySymbols) { diff --git a/packages/pretty-format/src/index.ts b/packages/pretty-format/src/index.ts index 0c305ae23cf4..1960daf96b41 100644 --- a/packages/pretty-format/src/index.ts +++ b/packages/pretty-format/src/index.ts @@ -34,12 +34,13 @@ const regExpToString = RegExp.prototype.toString; * Explicitly comparing typeof constructor to function avoids undefined as name * when mock identity-obj-proxy returns the key as the value for any key. */ -const getConstructorName = (val: new (...args: Array) => any) => +const getConstructorName = (val: new (...args: Array) => unknown) => (typeof val.constructor === 'function' && val.constructor.name) || 'Object'; /* global window */ /** Is val is equal to global window object? Works even if it does not exist :) */ -const isWindow = (val: any) => typeof window !== 'undefined' && val === window; +const isWindow = (val: unknown) => + typeof window !== 'undefined' && val === window; const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; const NEWLINE_REGEXP = /\n/gi; @@ -306,7 +307,7 @@ function printPlugin( return printed; } -function findPlugin(plugins: PrettyFormat.Plugins, val: any) { +function findPlugin(plugins: PrettyFormat.Plugins, val: unknown) { for (let p = 0; p < plugins.length; p++) { try { if (plugins[p].test(val)) { @@ -321,7 +322,7 @@ function findPlugin(plugins: PrettyFormat.Plugins, val: any) { } function printer( - val: any, + val: unknown, config: PrettyFormat.Config, indentation: string, depth: number, diff --git a/packages/pretty-format/src/plugins/lib/markup.ts b/packages/pretty-format/src/plugins/lib/markup.ts index d7b19a566ab2..13c5c4a0f750 100644 --- a/packages/pretty-format/src/plugins/lib/markup.ts +++ b/packages/pretty-format/src/plugins/lib/markup.ts @@ -55,7 +55,7 @@ export const printProps = ( // Return empty string if children is empty. export const printChildren = ( - children: Array, + children: Array, config: Config, indentation: string, depth: number, diff --git a/packages/test-utils/src/alignedAnsiStyleSerializer.ts b/packages/test-utils/src/alignedAnsiStyleSerializer.ts index a6325ef8341c..bc92b21d4969 100644 --- a/packages/test-utils/src/alignedAnsiStyleSerializer.ts +++ b/packages/test-utils/src/alignedAnsiStyleSerializer.ts @@ -7,8 +7,9 @@ import ansiRegex = require('ansi-regex'); import style = require('ansi-styles'); +import prettyFormat = require('pretty-format'); -export const alignedAnsiStyleSerializer = { +export const alignedAnsiStyleSerializer: prettyFormat.NewPlugin = { serialize(val: string): string { // Return the string itself, not escaped nor enclosed in double quote marks. return val.replace(ansiRegex(), match => { From f7f27f3d0c9ed2c2fea5776a8c3f4e626ce52166 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Mon, 14 Sep 2020 13:46:17 +0200 Subject: [PATCH 2/5] reinstate an any --- packages/jest-snapshot/src/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/jest-snapshot/src/types.ts b/packages/jest-snapshot/src/types.ts index 084379dab721..8dbd91c9c31a 100644 --- a/packages/jest-snapshot/src/types.ts +++ b/packages/jest-snapshot/src/types.ts @@ -21,7 +21,7 @@ export type MatchSnapshotConfig = { isInline: boolean; matcherName: string; properties?: object; - received: unknown; + received: any; }; export type SnapshotData = Record; From 86c62b7726ce768f2b18949b8a6c1fd0f6d4c948 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Mon, 14 Sep 2020 18:04:12 +0200 Subject: [PATCH 3/5] reinstate more anys --- packages/jest-runtime/src/index.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index e81d6020ec72..11f8ace43a99 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -158,8 +158,8 @@ class Runtime { string, jestMock.MockFunctionMetadata> >; - private _mockRegistry: Map; - private _isolatedMockRegistry: Map | null; + private _mockRegistry: Map; + private _isolatedMockRegistry: Map | null; private _moduleMocker: typeof jestMock; private _isolatedModuleRegistry: ModuleRegistry | null; private _moduleRegistry: ModuleRegistry; @@ -1049,7 +1049,7 @@ class Runtime { this.jestObjectCaches.set(filename, jestObject); - const lastArgs: [Jest | undefined, ...Array] = [ + const lastArgs: [Jest | undefined, ...Array] = [ this._config.injectGlobals ? jestObject : undefined, // jest object this._config.extraGlobals.map(globalVariable => { if (this._environment.global[globalVariable]) { @@ -1700,7 +1700,7 @@ class Runtime { beforeAll: this._environment.global.beforeAll, beforeEach: this._environment.global.beforeEach, describe: this._environment.global.describe, - expect: this._environment.global.expect as unknown, + expect: this._environment.global.expect as any, fdescribe: this._environment.global.fdescribe, fit: this._environment.global.fit, it: this._environment.global.it, From dcb7aeda5551027a50e5893d246ffacf74918d63 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Mon, 14 Sep 2020 18:14:39 +0200 Subject: [PATCH 4/5] fix util type --- e2e/Utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/Utils.ts b/e2e/Utils.ts index 547622a64d8d..fe3cfcedc2f9 100644 --- a/e2e/Utils.ts +++ b/e2e/Utils.ts @@ -65,7 +65,7 @@ export const linkJestPackage = (packageName: string, cwd: Config.Path) => { export const makeTemplate = ( str: string, -): ((values?: Array) => string) => (values?: unknown) => +): ((values?: Array) => string) => (values = []) => str.replace(/\$(\d+)/g, (_match, number) => { if (!Array.isArray(values)) { throw new Error('Array of values must be passed to the template.'); From 27754eb7616b993c78f9b0bd5a9f6b764d466be6 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Mon, 14 Sep 2020 18:22:41 +0200 Subject: [PATCH 5/5] why not --- e2e/Utils.ts | 18 +++++++++--------- package.json | 1 + yarn.lock | 1 + 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/e2e/Utils.ts b/e2e/Utils.ts index fe3cfcedc2f9..6da33e7d55fb 100644 --- a/e2e/Utils.ts +++ b/e2e/Utils.ts @@ -9,6 +9,7 @@ import * as path from 'path'; import * as fs from 'graceful-fs'; import type {Config} from '@jest/types'; import {ExecaReturnValue, sync as spawnSync} from 'execa'; +import type {PackageJson} from 'type-fest'; import rimraf = require('rimraf'); import dedent = require('dedent'); import which = require('which'); @@ -166,19 +167,18 @@ export const sortLines = (output: string) => .filter(Boolean) .join('\n'); +const DEFAULT_PACKAGE_JSON: PackageJson = { + description: 'THIS IS AN AUTOGENERATED FILE AND SHOULD NOT BE ADDED TO GIT', + jest: { + testEnvironment: 'node', + }, +}; + export const createEmptyPackage = ( directory: Config.Path, - packageJson?: {[keys: string]: unknown}, + packageJson = DEFAULT_PACKAGE_JSON, ) => { - const DEFAULT_PACKAGE_JSON = { - description: 'THIS IS AN AUTOGENERATED FILE AND SHOULD NOT BE ADDED TO GIT', - jest: { - testEnvironment: 'node', - }, - }; - fs.mkdirSync(directory, {recursive: true}); - packageJson || (packageJson = DEFAULT_PACKAGE_JSON); fs.writeFileSync( path.resolve(directory, 'package.json'), JSON.stringify(packageJson, null, 2), diff --git a/package.json b/package.json index 75763904f3e4..3af4c8c57840 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,7 @@ "strip-ansi": "^6.0.0", "tempy": "^0.6.0", "throat": "^5.0.0", + "type-fest": "^0.16.0", "typescript": "^4.0.2", "which": "^2.0.1" }, diff --git a/yarn.lock b/yarn.lock index e52658b4be4b..6f01c9063374 100644 --- a/yarn.lock +++ b/yarn.lock @@ -17097,6 +17097,7 @@ fsevents@^1.2.7: strip-ansi: ^6.0.0 tempy: ^0.6.0 throat: ^5.0.0 + type-fest: ^0.16.0 typescript: ^4.0.2 which: ^2.0.1 languageName: unknown