From 5d1e98beda19dcfff3f10557396098524efbb639 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Sun, 9 Feb 2020 22:41:49 +0100 Subject: [PATCH] chore: add explicit-module-boundary-types lint rule (#9539) --- .eslintrc.js | 18 ++++++++ package.json | 4 +- packages/babel-plugin-jest-hoist/src/index.ts | 2 +- packages/diff-sequences/src/index.ts | 2 +- packages/expect/src/asymmetricMatchers.ts | 26 ++++++------ packages/expect/src/jestMatchersObject.ts | 9 ++-- packages/expect/src/print.ts | 8 ++-- packages/expect/src/toThrowMatchers.ts | 8 +++- packages/expect/src/utils.ts | 26 ++++++++---- .../jest-circus/src/globalErrorHandlers.ts | 2 +- .../jestAdapterInit.ts | 2 + .../legacy-code-todo-rewrite/jestExpect.ts | 2 +- packages/jest-circus/src/utils.ts | 30 +++++++------ packages/jest-cli/src/cli/args.ts | 2 +- packages/jest-cli/src/cli/index.ts | 5 ++- packages/jest-cli/src/init/index.ts | 4 +- .../src/ReporterValidationErrors.ts | 4 +- packages/jest-config/src/color.ts | 2 +- packages/jest-config/src/importMjs.ts | 3 +- packages/jest-config/src/utils.ts | 12 +++--- packages/jest-config/src/validatePattern.ts | 2 +- packages/jest-console/src/BufferedConsole.ts | 34 +++++++-------- packages/jest-console/src/CustomConsole.ts | 35 ++++++++-------- packages/jest-console/src/NullConsole.ts | 26 ++++++------ packages/jest-console/src/getConsoleOutput.ts | 6 ++- packages/jest-core/src/FailedTestsCache.ts | 2 +- packages/jest-core/src/ReporterDispatcher.ts | 16 ++++--- packages/jest-core/src/SearchSource.ts | 2 +- .../jest-core/src/SnapshotInteractiveMode.ts | 14 +++---- .../jest-core/src/TestNamePatternPrompt.ts | 8 ++-- .../jest-core/src/TestPathPatternPrompt.ts | 6 +-- packages/jest-core/src/TestScheduler.ts | 9 ++-- packages/jest-core/src/TestWatcher.ts | 6 +-- packages/jest-core/src/collectHandles.ts | 2 +- .../jest-core/src/getNoTestFoundFailed.ts | 2 +- .../src/getNoTestFoundPassWithNoTests.ts | 2 +- .../getNoTestFoundRelatedToChangedFiles.ts | 2 +- packages/jest-core/src/lib/is_valid_path.ts | 2 +- packages/jest-core/src/pluralize.ts | 6 ++- packages/jest-core/src/runJest.ts | 6 +-- packages/jest-core/src/testSchedulerHelper.ts | 2 +- packages/jest-diff/src/joinAlignedDiffs.ts | 2 +- .../jest-diff/src/normalizeDiffOptions.ts | 2 +- packages/jest-diff/src/printDiffs.ts | 5 ++- packages/jest-docblock/src/index.ts | 2 +- packages/jest-each/src/validation.ts | 4 +- .../jest-fake-timers/src/FakeTimersLolex.ts | 26 ++++++------ .../jest-fake-timers/src/jestFakeTimers.ts | 26 ++++++------ packages/jest-haste-map/src/ModuleMap.ts | 4 +- packages/jest-jasmine2/src/isError.ts | 5 ++- .../jest-jasmine2/src/jasmineAsyncInstall.ts | 2 +- packages/jest-jasmine2/src/jestExpect.ts | 2 +- packages/jest-jasmine2/src/queueRunner.ts | 2 + packages/jest-jasmine2/src/reporter.ts | 4 +- .../jest-jasmine2/src/setup_jest_globals.ts | 3 +- packages/jest-jasmine2/src/treeProcessor.ts | 2 +- .../jest-matcher-utils/src/Replaceable.ts | 2 + packages/jest-matcher-utils/src/index.ts | 32 +++++++------- packages/jest-message-util/src/index.ts | 10 +++-- packages/jest-regex-util/src/index.ts | 6 +-- packages/jest-reporters/src/Status.ts | 19 +++++---- packages/jest-reporters/src/base_reporter.ts | 15 ++++--- .../jest-reporters/src/coverage_reporter.ts | 4 +- .../jest-reporters/src/default_reporter.ts | 16 +++---- .../jest-reporters/src/get_result_header.ts | 2 +- .../jest-reporters/src/summary_reporter.ts | 7 +++- packages/jest-reporters/src/utils.ts | 13 +++--- .../jest-reporters/src/verbose_reporter.ts | 6 +-- packages/jest-resolve/src/defaultResolver.ts | 4 +- packages/jest-runner/src/testWorker.ts | 2 +- packages/jest-runtime/src/cli/index.ts | 5 ++- packages/jest-serializer/src/index.ts | 2 +- packages/jest-snapshot/package.json | 2 +- packages/jest-snapshot/src/State.ts | 21 ++++++---- .../jest-snapshot/src/inline_snapshots.ts | 4 +- packages/jest-snapshot/src/plugins.ts | 4 +- packages/jest-snapshot/src/printSnapshot.ts | 8 ++-- packages/jest-snapshot/src/utils.ts | 7 ++-- packages/jest-source-map/src/getCallsite.ts | 5 ++- packages/jest-test-sequencer/src/index.ts | 6 +-- .../jest-transform/src/ScriptTransformer.ts | 16 ++++++- .../src/enhanceUnexpectedTokenMessage.ts | 10 +++-- packages/jest-util/src/clearLine.ts | 2 +- packages/jest-util/src/createDirectory.ts | 2 +- packages/jest-util/src/createProcessObject.ts | 2 +- .../jest-util/src/interopRequireDefault.ts | 3 +- packages/jest-util/src/pluralize.ts | 2 +- packages/jest-util/src/preRunMessage.ts | 4 +- packages/jest-util/src/setGlobal.ts | 2 +- .../jest-util/src/testPathPatternToRegExp.ts | 5 ++- packages/jest-validate/src/condition.ts | 13 ++++-- packages/jest-validate/src/errors.ts | 4 +- packages/jest-validate/src/utils.ts | 8 ++-- .../jest-validate/src/validateCLIOptions.ts | 2 +- packages/jest-watcher/src/PatternPrompt.ts | 4 +- packages/jest-watcher/src/lib/Prompt.ts | 14 +++---- packages/jest-watcher/src/lib/colorize.ts | 2 +- .../src/lib/formatTestNameByPattern.ts | 2 +- .../src/lib/patternModeHelpers.ts | 4 +- packages/jest-watcher/src/lib/scroll.ts | 5 ++- .../src/workers/ChildProcessWorker.ts | 14 ++++--- .../src/workers/NodeThreadsWorker.ts | 14 ++++--- packages/pretty-format/src/collections.ts | 7 +--- .../src/plugins/AsymmetricMatcher.ts | 7 ++-- .../pretty-format/src/plugins/ConvertAnsi.ts | 4 +- .../src/plugins/DOMCollection.ts | 6 +-- .../pretty-format/src/plugins/DOMElement.ts | 6 +-- .../pretty-format/src/plugins/Immutable.ts | 12 +++--- .../pretty-format/src/plugins/ReactElement.ts | 7 ++-- .../src/plugins/ReactTestComponent.ts | 7 ++-- .../pretty-format/src/plugins/lib/markup.ts | 4 +- packages/test-utils/src/ConditionalTest.ts | 13 +++--- .../src/alignedAnsiStyleSerializer.ts | 2 +- yarn.lock | 42 +++++++++---------- 114 files changed, 528 insertions(+), 377 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 7a9721db88f2..075a0c763dfd 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -73,6 +73,24 @@ module.exports = { 'import/no-extraneous-dependencies': 0, }, }, + { + files: 'packages/**/*.ts', + rules: { + '@typescript-eslint/explicit-module-boundary-types': 2, + }, + }, + { + files: [ + '**/__tests__/**', + '**/__mocks__/**', + 'packages/jest-jasmine2/src/jasmine/**/*', + 'packages/expect/src/jasmineUtils.ts', + '**/vendor/**/*', + ], + rules: { + '@typescript-eslint/explicit-module-boundary-types': 0, + }, + }, { files: [ 'packages/jest-jasmine2/src/jasmine/**/*', diff --git a/package.json b/package.json index 481cedfd43e5..4621e3274d86 100644 --- a/package.json +++ b/package.json @@ -17,8 +17,8 @@ "@types/jest": "24.0.2", "@types/node": "*", "@types/which": "^1.3.2", - "@typescript-eslint/eslint-plugin": "^2.2.0", - "@typescript-eslint/parser": "^2.2.0", + "@typescript-eslint/eslint-plugin": "^2.19.0", + "@typescript-eslint/parser": "^2.19.0", "ansi-regex": "^5.0.0", "ansi-styles": "^4.2.0", "babel-eslint": "^10.0.3", diff --git a/packages/babel-plugin-jest-hoist/src/index.ts b/packages/babel-plugin-jest-hoist/src/index.ts index e949ed6e0b9f..91f2742dfddc 100644 --- a/packages/babel-plugin-jest-hoist/src/index.ts +++ b/packages/babel-plugin-jest-hoist/src/index.ts @@ -155,7 +155,7 @@ FUNCTIONS.deepUnmock = args => args.length === 1 && args[0].isStringLiteral(); FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = args => args.length === 0; -export default () => { +export default (): {visitor: Visitor} => { const shouldHoistExpression = (expr: NodePath): boolean => { if (!expr.isCallExpression()) { return false; diff --git a/packages/diff-sequences/src/index.ts b/packages/diff-sequences/src/index.ts index 5dbbc4c6bd65..5426c242ce0a 100644 --- a/packages/diff-sequences/src/index.ts +++ b/packages/diff-sequences/src/index.ts @@ -785,7 +785,7 @@ export default ( bLength: number, isCommon: IsCommon, foundSubsequence: FoundSubsequence, -) => { +): void => { validateLength('aLength', aLength); validateLength('bLength', bLength); validateCallback('isCommon', isCommon); diff --git a/packages/expect/src/asymmetricMatchers.ts b/packages/expect/src/asymmetricMatchers.ts index 9ff897315936..fa7293e0eaaa 100644 --- a/packages/expect/src/asymmetricMatchers.ts +++ b/packages/expect/src/asymmetricMatchers.ts @@ -239,21 +239,23 @@ class StringMatching extends AsymmetricMatcher { } } -export const any = (expectedObject: any) => new Any(expectedObject); -export const anything = () => new Anything(); -export const arrayContaining = (sample: Array) => +export const any = (expectedObject: unknown): Any => new Any(expectedObject); +export const anything = (): Anything => new Anything(); +export const arrayContaining = (sample: Array): ArrayContaining => new ArrayContaining(sample); -export const arrayNotContaining = (sample: Array) => +export const arrayNotContaining = (sample: Array): ArrayContaining => new ArrayContaining(sample, true); -export const objectContaining = (sample: Record) => - new ObjectContaining(sample); -export const objectNotContaining = (sample: Record) => - new ObjectContaining(sample, true); -export const stringContaining = (expected: string) => +export const objectContaining = ( + sample: Record, +): ObjectContaining => new ObjectContaining(sample); +export const objectNotContaining = ( + sample: Record, +): ObjectContaining => new ObjectContaining(sample, true); +export const stringContaining = (expected: string): StringContaining => new StringContaining(expected); -export const stringNotContaining = (expected: string) => +export const stringNotContaining = (expected: string): StringContaining => new StringContaining(expected, true); -export const stringMatching = (expected: string | RegExp) => +export const stringMatching = (expected: string | RegExp): StringMatching => new StringMatching(expected); -export const stringNotMatching = (expected: string | RegExp) => +export const stringNotMatching = (expected: string | RegExp): StringMatching => new StringMatching(expected, true); diff --git a/packages/expect/src/jestMatchersObject.ts b/packages/expect/src/jestMatchersObject.ts index 7a35146558e3..1bc754a4b7ea 100644 --- a/packages/expect/src/jestMatchersObject.ts +++ b/packages/expect/src/jestMatchersObject.ts @@ -31,19 +31,20 @@ if (!global.hasOwnProperty(JEST_MATCHERS_OBJECT)) { }); } -export const getState = () => (global as any)[JEST_MATCHERS_OBJECT].state; +export const getState = (): any => (global as any)[JEST_MATCHERS_OBJECT].state; -export const setState = (state: object) => { +export const setState = (state: object): void => { Object.assign((global as any)[JEST_MATCHERS_OBJECT].state, state); }; -export const getMatchers = () => (global as any)[JEST_MATCHERS_OBJECT].matchers; +export const getMatchers = (): MatchersObject => + (global as any)[JEST_MATCHERS_OBJECT].matchers; export const setMatchers = ( matchers: MatchersObject, isInternal: boolean, expect: Expect, -) => { +): void => { Object.keys(matchers).forEach(key => { const matcher = matchers[key]; Object.defineProperty(matcher, INTERNAL_MATCHER_FLAG, { diff --git a/packages/expect/src/print.ts b/packages/expect/src/print.ts index 10aac847cf75..fbdd51350548 100644 --- a/packages/expect/src/print.ts +++ b/packages/expect/src/print.ts @@ -92,24 +92,24 @@ export const printCloseTo = ( export const printExpectedConstructorName = ( label: string, expected: Function, -) => printConstructorName(label, expected, false, true) + '\n'; +): string => printConstructorName(label, expected, false, true) + '\n'; export const printExpectedConstructorNameNot = ( label: string, expected: Function, -) => printConstructorName(label, expected, true, true) + '\n'; +): string => printConstructorName(label, expected, true, true) + '\n'; export const printReceivedConstructorName = ( label: string, received: Function, -) => printConstructorName(label, received, false, false) + '\n'; +): string => printConstructorName(label, received, false, false) + '\n'; // Do not call function if received is equal to expected. export const printReceivedConstructorNameNot = ( label: string, received: Function, expected: Function, -) => +): string => typeof expected.name === 'string' && expected.name.length !== 0 && typeof received.name === 'string' && diff --git a/packages/expect/src/toThrowMatchers.ts b/packages/expect/src/toThrowMatchers.ts index 0262f533df43..2c586f1dc922 100644 --- a/packages/expect/src/toThrowMatchers.ts +++ b/packages/expect/src/toThrowMatchers.ts @@ -27,6 +27,7 @@ import { printReceivedStringContainExpectedSubstring, } from './print'; import { + ExpectationResult, MatcherState, MatchersObject, RawMatcherFn, @@ -75,7 +76,12 @@ export const createMatcher = ( matcherName: string, fromPromise?: boolean, ): RawMatcherFn => - function(this: MatcherState, received: Function, expected: any) { + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + function( + this: MatcherState, + received: Function, + expected: any, + ): ExpectationResult { const options = { isNot: this.isNot, promise: this.promise, diff --git a/packages/expect/src/utils.ts b/packages/expect/src/utils.ts index d4763e9f4056..d386c8ad8edf 100644 --- a/packages/expect/src/utils.ts +++ b/packages/expect/src/utils.ts @@ -44,7 +44,7 @@ const hasGetterFromConstructor = (object: object, key: string) => { return descriptor !== undefined && typeof descriptor.get === 'function'; }; -export const hasOwnProperty = (object: object, key: string) => +export const hasOwnProperty = (object: object, key: string): boolean => Object.prototype.hasOwnProperty.call(object, key) || hasGetterFromConstructor(object, key); @@ -104,6 +104,7 @@ export const getPath = ( // Strip properties from object that are not present in the subset. Useful for // printing the diff for toMatchObject() without adding unrelated noise. +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const getObjectSubset = ( object: any, subset: any, @@ -147,12 +148,13 @@ const IteratorSymbol = Symbol.iterator; const hasIterator = (object: any) => !!(object != null && object[IteratorSymbol]); +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const iterableEquality = ( a: any, b: any, aStack: Array = [], bStack: Array = [], -) => { +): boolean | undefined => { if ( typeof a !== 'object' || typeof b !== 'object' || @@ -273,16 +275,17 @@ const isObjectWithKeys = (a: any) => !(a instanceof Array) && !(a instanceof Date); +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const subsetEquality = ( object: any, subset: any, -): undefined | boolean => { +): boolean | undefined => { // subsetEquality needs to keep track of the references // it has already visited to avoid infinite loops in case // there are circular references in the subset passed to it. const subsetEqualityWithContext = ( seenReferences: WeakMap = new WeakMap(), - ) => (object: any, subset: any): undefined | boolean => { + ) => (object: any, subset: any): boolean | undefined => { if (!isObjectWithKeys(subset)) { return undefined; } @@ -314,7 +317,8 @@ export const subsetEquality = ( return subsetEqualityWithContext()(object, subset); }; -export const typeEquality = (a: any, b: any) => { +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export const typeEquality = (a: any, b: any): boolean | undefined => { if (a == null || b == null || a.constructor === b.constructor) { return undefined; } @@ -322,7 +326,10 @@ export const typeEquality = (a: any, b: any) => { return false; }; -export const sparseArrayEquality = (a: unknown, b: unknown) => { +export const sparseArrayEquality = ( + a: unknown, + b: unknown, +): boolean | undefined => { if (!Array.isArray(a) || !Array.isArray(b)) { return undefined; } @@ -347,7 +354,7 @@ export const partition = ( }; // Copied from https://github.com/graingert/angular.js/blob/a43574052e9775cbc1d7dd8a086752c979b0f020/src/Angular.js#L685-L693 -export const isError = (value: unknown) => { +export const isError = (value: unknown): value is Error => { switch (Object.prototype.toString.call(value)) { case '[object Error]': return true; @@ -360,13 +367,14 @@ export const isError = (value: unknown) => { } }; -export function emptyObject(obj: any) { +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export function emptyObject(obj: any): boolean { return obj && typeof obj === 'object' ? !Object.keys(obj).length : false; } const MULTILINE_REGEXP = /[\r\n]/; -export const isOneline = (expected: any, received: any): boolean => +export const isOneline = (expected: unknown, received: unknown): boolean => typeof expected === 'string' && typeof received === 'string' && (!MULTILINE_REGEXP.test(expected) || !MULTILINE_REGEXP.test(received)); diff --git a/packages/jest-circus/src/globalErrorHandlers.ts b/packages/jest-circus/src/globalErrorHandlers.ts index a48763f8f24c..c3e7b7228f5e 100644 --- a/packages/jest-circus/src/globalErrorHandlers.ts +++ b/packages/jest-circus/src/globalErrorHandlers.ts @@ -28,7 +28,7 @@ export const injectGlobalErrorHandlers = ( export const restoreGlobalErrorHandlers = ( parentProcess: NodeJS.Process, originalErrorHandlers: Circus.GlobalErrorHandlers, -) => { +): void => { parentProcess.removeListener('uncaughtException', uncaught); parentProcess.removeListener('unhandledRejection', uncaught); 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 0b0f92095ba3..bceca84537e8 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts @@ -34,6 +34,8 @@ import globals from '..'; type Process = NodeJS.Process; +// TODO: hard to type +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const initialize = ({ config, environment, diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts index fa5436dbaf94..8633be79fe97 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestExpect.ts @@ -15,7 +15,7 @@ import { toThrowErrorMatchingSnapshot, } from 'jest-snapshot'; -export default (config: {expand: boolean}) => { +export default (config: {expand: boolean}): void => { global.expect = expect; expect.setState({ expand: config.expand, diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts index 240c42c46f3d..7594cbd5f47d 100644 --- a/packages/jest-circus/src/utils.ts +++ b/packages/jest-circus/src/utils.ts @@ -73,11 +73,15 @@ const hasEnabledTest = (describeBlock: Circus.DescribeBlock): boolean => { return hasOwnEnabledTests || describeBlock.children.some(hasEnabledTest); }; -export const getAllHooksForDescribe = (describe: Circus.DescribeBlock) => { - const result: { - beforeAll: Array; - afterAll: Array; - } = { +type DescribeHooks = { + beforeAll: Array; + afterAll: Array; +}; + +export const getAllHooksForDescribe = ( + describe: Circus.DescribeBlock, +): DescribeHooks => { + const result: DescribeHooks = { afterAll: [], beforeAll: [], }; @@ -98,11 +102,13 @@ export const getAllHooksForDescribe = (describe: Circus.DescribeBlock) => { return result; }; -export const getEachHooksForTest = (test: Circus.TestEntry) => { - const result: { - beforeEach: Array; - afterEach: Array; - } = {afterEach: [], beforeEach: []}; +type TestHooks = { + beforeEach: Array; + afterEach: Array; +}; + +export const getEachHooksForTest = (test: Circus.TestEntry): TestHooks => { + const result: TestHooks = {afterEach: [], beforeEach: []}; let block: Circus.DescribeBlock | undefined | null = test.parent; do { @@ -298,7 +304,7 @@ const makeTestResults = ( // Return a string that identifies the test (concat of parent describe block // names + test title) -export const getTestID = (test: Circus.TestEntry) => { +export const getTestID = (test: Circus.TestEntry): string => { const titles = []; let parent: Circus.TestEntry | Circus.DescribeBlock | undefined = test; do { @@ -341,7 +347,7 @@ export const addErrorToEachTestUnderDescribe = ( describeBlock: Circus.DescribeBlock, error: Circus.Exception, asyncError: Circus.Exception, -) => { +): void => { for (const test of describeBlock.tests) { test.errors.push([error, asyncError]); } diff --git a/packages/jest-cli/src/cli/args.ts b/packages/jest-cli/src/cli/args.ts index 422dd698c879..6fac72522c06 100644 --- a/packages/jest-cli/src/cli/args.ts +++ b/packages/jest-cli/src/cli/args.ts @@ -9,7 +9,7 @@ import {Config} from '@jest/types'; import {isJSONString} from 'jest-config'; import isCI = require('is-ci'); -export const check = (argv: Config.Argv) => { +export const check = (argv: Config.Argv): true => { if (argv.runInBand && argv.hasOwnProperty('maxWorkers')) { throw new Error( 'Both --runInBand and --maxWorkers were specified, but these two ' + diff --git a/packages/jest-cli/src/cli/index.ts b/packages/jest-cli/src/cli/index.ts index c4024ea7aab1..c31d18e1a24e 100644 --- a/packages/jest-cli/src/cli/index.ts +++ b/packages/jest-cli/src/cli/index.ts @@ -19,7 +19,10 @@ import {sync as realpath} from 'realpath-native'; import init from '../init'; import * as args from './args'; -export async function run(maybeArgv?: Array, project?: Config.Path) { +export async function run( + maybeArgv?: Array, + project?: Config.Path, +): Promise { try { const argv: Config.Argv = buildArgv(maybeArgv); diff --git a/packages/jest-cli/src/init/index.ts b/packages/jest-cli/src/init/index.ts index faafb4792bf8..ce23c39b313f 100644 --- a/packages/jest-cli/src/init/index.ts +++ b/packages/jest-cli/src/init/index.ts @@ -34,7 +34,9 @@ type PromptsResults = { const getConfigFilename = (ext: string) => JEST_CONFIG_BASE_NAME + ext; -export default async (rootDir: string = realpath(process.cwd())) => { +export default async ( + rootDir: string = realpath(process.cwd()), +): Promise => { // prerequisite checks const projectPackageJsonPath: string = path.join(rootDir, PACKAGE_JSON); diff --git a/packages/jest-config/src/ReporterValidationErrors.ts b/packages/jest-config/src/ReporterValidationErrors.ts index 8137dedd61cb..3726cc524c92 100644 --- a/packages/jest-config/src/ReporterValidationErrors.ts +++ b/packages/jest-config/src/ReporterValidationErrors.ts @@ -25,7 +25,7 @@ const ERROR = `${BULLET}Reporter Validation Error`; export function createReporterError( reporterIndex: number, reporterValue: Array | string, -) { +): ValidationError { const errorMessage = ` Reporter at index ${reporterIndex} must be of type:\n` + ` ${chalk.bold.green(validReporterTypes.join(' or '))}\n` + @@ -42,7 +42,7 @@ export function createArrayReporterError( value: string | Record, expectedType: string, valueName: string, -) { +): ValidationError { const errorMessage = ` Unexpected value for ${valueName} ` + `at index ${valueIndex} of reporter at index ${reporterIndex}\n` + diff --git a/packages/jest-config/src/color.ts b/packages/jest-config/src/color.ts index f7fdd5317f5c..78f15a5398ce 100644 --- a/packages/jest-config/src/color.ts +++ b/packages/jest-config/src/color.ts @@ -18,7 +18,7 @@ const colors: Array = [ 'white', ]; -export const getDisplayNameColor = (seed?: string) => { +export const getDisplayNameColor = (seed?: string): typeof colors[number] => { if (seed === undefined) { return 'white'; } diff --git a/packages/jest-config/src/importMjs.ts b/packages/jest-config/src/importMjs.ts index d04ddf5525d3..693bac33185b 100644 --- a/packages/jest-config/src/importMjs.ts +++ b/packages/jest-config/src/importMjs.ts @@ -7,4 +7,5 @@ // this is in a separate file so that node 8 don't explode with a syntax error. // Remove this file when we drop support for Node 8 -export default (specifier: string) => import(specifier); +export default (specifier: string): Promise<{default: unknown}> => + import(specifier); diff --git a/packages/jest-config/src/utils.ts b/packages/jest-config/src/utils.ts index 1fe8c244d3c9..44cc7dc1e492 100644 --- a/packages/jest-config/src/utils.ts +++ b/packages/jest-config/src/utils.ts @@ -31,7 +31,7 @@ const createValidationError = (message: string) => export const resolve = ( resolver: string | null | undefined, {key, filePath, rootDir, optional}: ResolveOptions, -) => { +): string => { const module = Resolver.findNodeModule( replaceRootDirInPath(rootDir, filePath), { @@ -132,7 +132,7 @@ export const resolveWithPrefix = ( prefix: string; rootDir: Config.Path; }, -) => { +): string => { const fileName = replaceRootDirInPath(rootDir, filePath); let module = Resolver.findNodeModule(`${prefix}${fileName}`, { basedir: rootDir, @@ -181,7 +181,7 @@ export const getTestEnvironment = ({ }: { rootDir: Config.Path; testEnvironment: string; -}) => +}): string => resolveWithPrefix(undefined, { filePath, humanOptionName: 'Test environment', @@ -201,7 +201,7 @@ export const getTestEnvironment = ({ export const getWatchPlugin = ( resolver: string | undefined | null, {filePath, rootDir}: {filePath: string; rootDir: Config.Path}, -) => +): string => resolveWithPrefix(resolver, { filePath, humanOptionName: 'Watch plugin', @@ -221,7 +221,7 @@ export const getWatchPlugin = ( export const getRunner = ( resolver: string | undefined | null, {filePath, rootDir}: {filePath: string; rootDir: Config.Path}, -) => +): string => resolveWithPrefix(resolver, { filePath, humanOptionName: 'Jest Runner', @@ -240,7 +240,7 @@ export const isJSONString = (text?: JSONString | string): text is JSONString => export const getSequencer = ( resolver: string | undefined | null, {filePath, rootDir}: {filePath: string; rootDir: Config.Path}, -) => +): string => resolveWithPrefix(resolver, { filePath, humanOptionName: 'Jest Sequencer', diff --git a/packages/jest-config/src/validatePattern.ts b/packages/jest-config/src/validatePattern.ts index 476a0b271f46..b132e09c0a6c 100644 --- a/packages/jest-config/src/validatePattern.ts +++ b/packages/jest-config/src/validatePattern.ts @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -export default function validatePattern(pattern?: string) { +export default function validatePattern(pattern?: string): boolean { if (pattern) { try { // eslint-disable-next-line no-new diff --git a/packages/jest-console/src/BufferedConsole.ts b/packages/jest-console/src/BufferedConsole.ts index fd60ec8c5287..17225d3d46f0 100644 --- a/packages/jest-console/src/BufferedConsole.ts +++ b/packages/jest-console/src/BufferedConsole.ts @@ -47,7 +47,7 @@ export default class BufferedConsole extends Console { message: LogMessage, level?: number | null, sourceMaps?: SourceMapRegistry | null, - ) { + ): ConsoleBuffer { const callsite = getCallsite(level != null ? level : 2, sourceMaps); const origin = callsite.getFileName() + ':' + callsite.getLineNumber(); @@ -70,7 +70,7 @@ export default class BufferedConsole extends Console { ); } - assert(value: any, message?: string | Error) { + assert(value: unknown, message?: string | Error): void { try { assert(value, message); } catch (error) { @@ -78,7 +78,7 @@ export default class BufferedConsole extends Console { } } - count(label: string = 'default') { + count(label: string = 'default'): void { if (!this._counters[label]) { this._counters[label] = 0; } @@ -86,27 +86,27 @@ export default class BufferedConsole extends Console { this._log('count', format(`${label}: ${++this._counters[label]}`)); } - countReset(label: string = 'default') { + countReset(label: string = 'default'): void { this._counters[label] = 0; } - debug(firstArg: any, ...rest: Array) { + debug(firstArg: unknown, ...rest: Array): void { this._log('debug', format(firstArg, ...rest)); } - dir(firstArg: any, ...rest: Array) { + dir(firstArg: unknown, ...rest: Array): void { this._log('dir', format(firstArg, ...rest)); } - dirxml(firstArg: any, ...rest: Array) { + dirxml(firstArg: unknown, ...rest: Array): void { this._log('dirxml', format(firstArg, ...rest)); } - error(firstArg: any, ...rest: Array) { + error(firstArg: unknown, ...rest: Array): void { this._log('error', format(firstArg, ...rest)); } - group(title?: string, ...rest: Array) { + group(title?: string, ...rest: Array): void { this._groupDepth++; if (title || rest.length > 0) { @@ -114,7 +114,7 @@ export default class BufferedConsole extends Console { } } - groupCollapsed(title?: string, ...rest: Array) { + groupCollapsed(title?: string, ...rest: Array): void { this._groupDepth++; if (title || rest.length > 0) { @@ -122,21 +122,21 @@ export default class BufferedConsole extends Console { } } - groupEnd() { + groupEnd(): void { if (this._groupDepth > 0) { this._groupDepth--; } } - info(firstArg: any, ...rest: Array) { + info(firstArg: unknown, ...rest: Array): void { this._log('info', format(firstArg, ...rest)); } - log(firstArg: any, ...rest: Array) { + log(firstArg: unknown, ...rest: Array): void { this._log('log', format(firstArg, ...rest)); } - time(label: string = 'default') { + time(label: string = 'default'): void { if (this._timers[label]) { return; } @@ -144,7 +144,7 @@ export default class BufferedConsole extends Console { this._timers[label] = new Date(); } - timeEnd(label: string = 'default') { + timeEnd(label: string = 'default'): void { const startTime = this._timers[label]; if (startTime) { @@ -155,11 +155,11 @@ export default class BufferedConsole extends Console { } } - warn(firstArg: any, ...rest: Array) { + warn(firstArg: unknown, ...rest: Array): void { this._log('warn', format(firstArg, ...rest)); } - getBuffer() { + getBuffer(): ConsoleBuffer | undefined { return this._buffer.length ? this._buffer : undefined; } } diff --git a/packages/jest-console/src/CustomConsole.ts b/packages/jest-console/src/CustomConsole.ts index c7b12ea69faf..d629995beb07 100644 --- a/packages/jest-console/src/CustomConsole.ts +++ b/packages/jest-console/src/CustomConsole.ts @@ -25,7 +25,8 @@ export default class CustomConsole extends Console { constructor( stdout: NodeJS.WriteStream, stderr: NodeJS.WriteStream, - formatBuffer: Formatter = (_type, message) => message, + formatBuffer: Formatter = (_type: LogType, message: string): string => + message, ) { super(stdout, stderr); this._stdout = stdout; @@ -50,7 +51,7 @@ export default class CustomConsole extends Console { ); } - assert(value: any, message?: string | Error) { + assert(value: unknown, message?: string | Error): asserts value { try { assert(value, message); } catch (error) { @@ -58,7 +59,7 @@ export default class CustomConsole extends Console { } } - count(label: string = 'default') { + count(label: string = 'default'): void { if (!this._counters[label]) { this._counters[label] = 0; } @@ -66,27 +67,27 @@ export default class CustomConsole extends Console { this._log('count', format(`${label}: ${++this._counters[label]}`)); } - countReset(label: string = 'default') { + countReset(label: string = 'default'): void { this._counters[label] = 0; } - debug(firstArg: any, ...args: Array) { + debug(firstArg: unknown, ...args: Array): void { this._log('debug', format(firstArg, ...args)); } - dir(firstArg: any, ...args: Array) { + dir(firstArg: unknown, ...args: Array): void { this._log('dir', format(firstArg, ...args)); } - dirxml(firstArg: any, ...args: Array) { + dirxml(firstArg: unknown, ...args: Array): void { this._log('dirxml', format(firstArg, ...args)); } - error(firstArg: any, ...args: Array) { + error(firstArg: unknown, ...args: Array): void { this._logError('error', format(firstArg, ...args)); } - group(title?: string, ...args: Array) { + group(title?: string, ...args: Array): void { this._groupDepth++; if (title || args.length > 0) { @@ -94,7 +95,7 @@ export default class CustomConsole extends Console { } } - groupCollapsed(title?: string, ...args: Array) { + groupCollapsed(title?: string, ...args: Array): void { this._groupDepth++; if (title || args.length > 0) { @@ -102,21 +103,21 @@ export default class CustomConsole extends Console { } } - groupEnd() { + groupEnd(): void { if (this._groupDepth > 0) { this._groupDepth--; } } - info(firstArg: any, ...args: Array) { + info(firstArg: unknown, ...args: Array): void { this._log('info', format(firstArg, ...args)); } - log(firstArg: any, ...args: Array) { + log(firstArg: unknown, ...args: Array): void { this._log('log', format(firstArg, ...args)); } - time(label: string = 'default') { + time(label: string = 'default'): void { if (this._timers[label]) { return; } @@ -124,7 +125,7 @@ export default class CustomConsole extends Console { this._timers[label] = new Date(); } - timeEnd(label: string = 'default') { + timeEnd(label: string = 'default'): void { const startTime = this._timers[label]; if (startTime) { @@ -135,11 +136,11 @@ export default class CustomConsole extends Console { } } - warn(firstArg: any, ...args: Array) { + warn(firstArg: unknown, ...args: Array): void { this._logError('warn', format(firstArg, ...args)); } - getBuffer() { + getBuffer(): undefined { return undefined; } } diff --git a/packages/jest-console/src/NullConsole.ts b/packages/jest-console/src/NullConsole.ts index 18336116e44a..1f3530d977a4 100644 --- a/packages/jest-console/src/NullConsole.ts +++ b/packages/jest-console/src/NullConsole.ts @@ -8,17 +8,17 @@ import CustomConsole from './CustomConsole'; export default class NullConsole extends CustomConsole { - assert() {} - debug() {} - dir() {} - error() {} - info() {} - log() {} - time() {} - timeEnd() {} - trace() {} - warn() {} - group() {} - groupCollapsed() {} - groupEnd() {} + assert(): void {} + debug(): void {} + dir(): void {} + error(): void {} + info(): void {} + log(): void {} + time(): void {} + timeEnd(): void {} + trace(): void {} + warn(): void {} + group(): void {} + groupCollapsed(): void {} + groupEnd(): void {} } diff --git a/packages/jest-console/src/getConsoleOutput.ts b/packages/jest-console/src/getConsoleOutput.ts index 60ad4f70a763..80097b76ad08 100644 --- a/packages/jest-console/src/getConsoleOutput.ts +++ b/packages/jest-console/src/getConsoleOutput.ts @@ -10,7 +10,11 @@ import chalk = require('chalk'); import slash = require('slash'); import {ConsoleBuffer} from './types'; -export default (root: string, verbose: boolean, buffer: ConsoleBuffer) => { +export default ( + root: string, + verbose: boolean, + buffer: ConsoleBuffer, +): string => { const TITLE_INDENT = verbose ? ' ' : ' '; const CONSOLE_INDENT = TITLE_INDENT + ' '; diff --git a/packages/jest-core/src/FailedTestsCache.ts b/packages/jest-core/src/FailedTestsCache.ts index 2285df36afa5..095aad123aae 100644 --- a/packages/jest-core/src/FailedTestsCache.ts +++ b/packages/jest-core/src/FailedTestsCache.ts @@ -23,7 +23,7 @@ export default class FailedTestsCache { return tests.filter(testResult => enabledTestsMap[testResult.path]); } - setTestResults(testResults: Array) { + setTestResults(testResults: Array): void { this._enabledTestsMap = (testResults || []) .filter(testResult => testResult.numFailingTests) .reduce((suiteMap, testResult) => { diff --git a/packages/jest-core/src/ReporterDispatcher.ts b/packages/jest-core/src/ReporterDispatcher.ts index e76caf596919..1e3907f90e2d 100644 --- a/packages/jest-core/src/ReporterDispatcher.ts +++ b/packages/jest-core/src/ReporterDispatcher.ts @@ -21,7 +21,7 @@ export default class ReporterDispatcher { this._reporters.push(reporter); } - unregister(ReporterClass: Function) { + unregister(ReporterClass: Function): void { this._reporters = this._reporters.filter( reporter => !(reporter instanceof ReporterClass), ); @@ -31,7 +31,7 @@ export default class ReporterDispatcher { test: Test, testResult: TestResult, results: AggregatedResult, - ) { + ): Promise { for (const reporter of this._reporters) { reporter.onTestResult && (await reporter.onTestResult(test, testResult, results)); @@ -43,19 +43,25 @@ export default class ReporterDispatcher { testResult.console = undefined; } - async onTestStart(test: Test) { + async onTestStart(test: Test): Promise { for (const reporter of this._reporters) { reporter.onTestStart && (await reporter.onTestStart(test)); } } - async onRunStart(results: AggregatedResult, options: ReporterOnStartOptions) { + async onRunStart( + results: AggregatedResult, + options: ReporterOnStartOptions, + ): Promise { for (const reporter of this._reporters) { reporter.onRunStart && (await reporter.onRunStart(results, options)); } } - async onRunComplete(contexts: Set, results: AggregatedResult) { + async onRunComplete( + contexts: Set, + results: AggregatedResult, + ): Promise { for (const reporter of this._reporters) { reporter.onRunComplete && (await reporter.onRunComplete(contexts, results)); diff --git a/packages/jest-core/src/SearchSource.ts b/packages/jest-core/src/SearchSource.ts index adb00e35f4f7..4a4900b324ee 100644 --- a/packages/jest-core/src/SearchSource.ts +++ b/packages/jest-core/src/SearchSource.ts @@ -238,7 +238,7 @@ export default class SearchSource { findTestRelatedToChangedFiles( changedFilesInfo: ChangedFiles, collectCoverage: boolean, - ) { + ): SearchResult { const {repos, changedFiles} = changedFilesInfo; // no SCM (git/hg/...) is found in any of the roots. const noSCM = (Object.keys(repos) as Array< diff --git a/packages/jest-core/src/SnapshotInteractiveMode.ts b/packages/jest-core/src/SnapshotInteractiveMode.ts index 0bea51b6bc84..86968b26a6cc 100644 --- a/packages/jest-core/src/SnapshotInteractiveMode.ts +++ b/packages/jest-core/src/SnapshotInteractiveMode.ts @@ -30,11 +30,11 @@ export default class SnapshotInteractiveMode { this._skippedNum = 0; } - isActive() { + isActive(): boolean { return this._isActive; } - getSkippedNum() { + getSkippedNum(): number { return this._skippedNum; } @@ -154,7 +154,7 @@ export default class SnapshotInteractiveMode { return this._drawUIProgress(); } - put(key: string) { + put(key: string): void { switch (key) { case 's': if (this._skippedNum === this._testAssertions.length) break; @@ -191,19 +191,19 @@ export default class SnapshotInteractiveMode { } } - abort() { + abort(): void { this._isActive = false; this._skippedNum = 0; this._updateTestRunnerConfig(null, false); } - restart() { + restart(): void { this._skippedNum = 0; this._countPaths = this._testAssertions.length; this._run(false); } - updateWithResults(results: AggregatedResult) { + updateWithResults(results: AggregatedResult): void { const hasSnapshotFailure = !!results.snapshot.failure; if (hasSnapshotFailure) { this._drawUIOverlay(); @@ -231,7 +231,7 @@ export default class SnapshotInteractiveMode { assertion: AssertionLocation | null, shouldUpdateSnapshot: boolean, ) => unknown, - ) { + ): void { if (!failedSnapshotTestAssertions.length) { return; } diff --git a/packages/jest-core/src/TestNamePatternPrompt.ts b/packages/jest-core/src/TestNamePatternPrompt.ts index d996e91cf2bf..9de302651ab8 100644 --- a/packages/jest-core/src/TestNamePatternPrompt.ts +++ b/packages/jest-core/src/TestNamePatternPrompt.ts @@ -24,18 +24,18 @@ export default class TestNamePatternPrompt extends PatternPrompt { this._cachedTestResults = []; } - _onChange(pattern: string, options: ScrollOptions) { + _onChange(pattern: string, options: ScrollOptions): void { super._onChange(pattern, options); this._printPrompt(pattern); } - _printPrompt(pattern: string) { + _printPrompt(pattern: string): void { const pipe = this._pipe; printPatternCaret(pattern, pipe); printRestoredPatternCaret(pattern, this._currentUsageRows, pipe); } - _getMatchedTests(pattern: string) { + _getMatchedTests(pattern: string): Array { let regex: RegExp; try { @@ -57,7 +57,7 @@ export default class TestNamePatternPrompt extends PatternPrompt { return matchedTests; } - updateCachedTestResults(testResults: Array = []) { + updateCachedTestResults(testResults: Array = []): void { this._cachedTestResults = testResults; } } diff --git a/packages/jest-core/src/TestPathPatternPrompt.ts b/packages/jest-core/src/TestPathPatternPrompt.ts index 47922c4e91c5..6d9cd7fe0a00 100644 --- a/packages/jest-core/src/TestPathPatternPrompt.ts +++ b/packages/jest-core/src/TestPathPatternPrompt.ts @@ -31,12 +31,12 @@ export default class TestPathPatternPrompt extends PatternPrompt { this._entityName = 'filenames'; } - _onChange(pattern: string, options: ScrollOptions) { + _onChange(pattern: string, options: ScrollOptions): void { super._onChange(pattern, options); this._printPrompt(pattern); } - _printPrompt(pattern: string) { + _printPrompt(pattern: string): void { const pipe = this._pipe; printPatternCaret(pattern, pipe); printRestoredPatternCaret(pattern, this._currentUsageRows, pipe); @@ -59,7 +59,7 @@ export default class TestPathPatternPrompt extends PatternPrompt { return tests; } - updateSearchSources(searchSources: SearchSources) { + updateSearchSources(searchSources: SearchSources): void { this._searchSources = searchSources; } } diff --git a/packages/jest-core/src/TestScheduler.ts b/packages/jest-core/src/TestScheduler.ts index 58a141136ea4..e3901da14834 100644 --- a/packages/jest-core/src/TestScheduler.ts +++ b/packages/jest-core/src/TestScheduler.ts @@ -63,15 +63,18 @@ export default class TestScheduler { this._setupReporters(); } - addReporter(reporter: Reporter) { + addReporter(reporter: Reporter): void { this._dispatcher.register(reporter); } - removeReporter(ReporterClass: Function) { + removeReporter(ReporterClass: Function): void { this._dispatcher.unregister(ReporterClass); } - async scheduleTests(tests: Array, watcher: TestWatcher) { + async scheduleTests( + tests: Array, + watcher: TestWatcher, + ): Promise { const onStart = this._dispatcher.onTestStart.bind(this._dispatcher); const timings: Array = []; const contexts = new Set(); diff --git a/packages/jest-core/src/TestWatcher.ts b/packages/jest-core/src/TestWatcher.ts index fce64763633a..750dcbe45efc 100644 --- a/packages/jest-core/src/TestWatcher.ts +++ b/packages/jest-core/src/TestWatcher.ts @@ -21,16 +21,16 @@ export default class TestWatcher extends EventEmitter { this._isWatchMode = isWatchMode; } - setState(state: State) { + setState(state: State): void { Object.assign(this.state, state); this.emit('change', this.state); } - isInterrupted() { + isInterrupted(): boolean { return this.state.interrupted; } - isWatchMode() { + isWatchMode(): boolean { return this._isWatchMode; } } diff --git a/packages/jest-core/src/collectHandles.ts b/packages/jest-core/src/collectHandles.ts index 1e4eba2e16cb..bbb1d92f5819 100644 --- a/packages/jest-core/src/collectHandles.ts +++ b/packages/jest-core/src/collectHandles.ts @@ -80,7 +80,7 @@ export default function collectHandles(): () => Array { hook.enable(); - return () => { + return (): Array => { hook.disable(); // Get errors for every async resource still referenced at this moment diff --git a/packages/jest-core/src/getNoTestFoundFailed.ts b/packages/jest-core/src/getNoTestFoundFailed.ts index ec448781b695..c34f043c0d7b 100644 --- a/packages/jest-core/src/getNoTestFoundFailed.ts +++ b/packages/jest-core/src/getNoTestFoundFailed.ts @@ -7,7 +7,7 @@ import chalk = require('chalk'); -export default function getNoTestFoundFailed() { +export default function getNoTestFoundFailed(): string { return ( chalk.bold('No failed test found.\n') + chalk.dim('Press `f` to quit "only failed tests" mode.') diff --git a/packages/jest-core/src/getNoTestFoundPassWithNoTests.ts b/packages/jest-core/src/getNoTestFoundPassWithNoTests.ts index 15a808b6a52a..174b1af14362 100644 --- a/packages/jest-core/src/getNoTestFoundPassWithNoTests.ts +++ b/packages/jest-core/src/getNoTestFoundPassWithNoTests.ts @@ -7,6 +7,6 @@ import chalk = require('chalk'); -export default function getNoTestFoundPassWithNoTests() { +export default function getNoTestFoundPassWithNoTests(): string { return chalk.bold('No tests found, exiting with code 0'); } diff --git a/packages/jest-core/src/getNoTestFoundRelatedToChangedFiles.ts b/packages/jest-core/src/getNoTestFoundRelatedToChangedFiles.ts index 59aae5f978fc..a42c93abc0e3 100644 --- a/packages/jest-core/src/getNoTestFoundRelatedToChangedFiles.ts +++ b/packages/jest-core/src/getNoTestFoundRelatedToChangedFiles.ts @@ -11,7 +11,7 @@ import {isInteractive} from 'jest-util'; export default function getNoTestFoundRelatedToChangedFiles( globalConfig: Config.GlobalConfig, -) { +): string { const ref = globalConfig.changedSince ? `"${globalConfig.changedSince}"` : 'last commit'; diff --git a/packages/jest-core/src/lib/is_valid_path.ts b/packages/jest-core/src/lib/is_valid_path.ts index a836154b65e1..d37dd14e9774 100644 --- a/packages/jest-core/src/lib/is_valid_path.ts +++ b/packages/jest-core/src/lib/is_valid_path.ts @@ -11,7 +11,7 @@ import {isSnapshotPath} from 'jest-snapshot'; export default function isValidPath( globalConfig: Config.GlobalConfig, filePath: Config.Path, -) { +): boolean { return ( !filePath.includes(globalConfig.coverageDirectory) && !isSnapshotPath(filePath) diff --git a/packages/jest-core/src/pluralize.ts b/packages/jest-core/src/pluralize.ts index bda5b9a328bc..2e0dadda77c8 100644 --- a/packages/jest-core/src/pluralize.ts +++ b/packages/jest-core/src/pluralize.ts @@ -5,6 +5,10 @@ * LICENSE file in the root directory of this source tree. */ -export default function pluralize(word: string, count: number, ending: string) { +export default function pluralize( + word: string, + count: number, + ending: string, +): string { return `${count} ${word}${count === 1 ? '' : ending}`; } diff --git a/packages/jest-core/src/runJest.ts b/packages/jest-core/src/runJest.ts index 3c62fe583951..c8fbb8754fc3 100644 --- a/packages/jest-core/src/runJest.ts +++ b/packages/jest-core/src/runJest.ts @@ -144,7 +144,7 @@ export default async function runJest({ onComplete: (testResults: AggregatedResult) => void; failedTestsCache?: FailedTestsCache; filter?: Filter; -}) { +}): Promise { const Sequencer: typeof TestSequencer = interopRequireDefault( require(globalConfig.testSequencer), ).default; @@ -195,7 +195,7 @@ export default async function runJest({ } onComplete && onComplete(makeEmptyAggregatedTestResult()); - return null; + return; } if (globalConfig.onlyFailures && failedTestsCache) { @@ -260,7 +260,7 @@ export default async function runJest({ await runGlobalHook({allTests, globalConfig, moduleName: 'globalTeardown'}); } - return processResults(results, { + await processResults(results, { collectHandles, json: globalConfig.json, onComplete, diff --git a/packages/jest-core/src/testSchedulerHelper.ts b/packages/jest-core/src/testSchedulerHelper.ts index 8fe17525aec6..5866030184e1 100644 --- a/packages/jest-core/src/testSchedulerHelper.ts +++ b/packages/jest-core/src/testSchedulerHelper.ts @@ -14,7 +14,7 @@ export function shouldRunInBand( tests: Array, timings: Array, {detectOpenHandles, maxWorkers, watch, watchAll}: Config.GlobalConfig, -) { +): boolean { // detectOpenHandles makes no sense without runInBand, because it cannot detect leaks in workers if (detectOpenHandles) { return true; diff --git a/packages/jest-diff/src/joinAlignedDiffs.ts b/packages/jest-diff/src/joinAlignedDiffs.ts index ebfb69078c18..7c69e9e2445c 100644 --- a/packages/jest-diff/src/joinAlignedDiffs.ts +++ b/packages/jest-diff/src/joinAlignedDiffs.ts @@ -198,7 +198,7 @@ export const joinAlignedDiffsNoExpand = ( export const joinAlignedDiffsExpand = ( diffs: Array, options: DiffOptionsNormalized, -) => +): string => diffs .map((diff: Diff, i: number, diffs: Array): string => { const line = diff[1]; diff --git a/packages/jest-diff/src/normalizeDiffOptions.ts b/packages/jest-diff/src/normalizeDiffOptions.ts index 1dbe1110dd19..6ba1e93c561a 100644 --- a/packages/jest-diff/src/normalizeDiffOptions.ts +++ b/packages/jest-diff/src/normalizeDiffOptions.ts @@ -9,7 +9,7 @@ import chalk = require('chalk'); import {DiffOptions, DiffOptionsNormalized} from './types'; -export const noColor = (string: string) => string; +export const noColor = (string: string): string => string; const DIFF_CONTEXT_DEFAULT = 5; diff --git a/packages/jest-diff/src/printDiffs.ts b/packages/jest-diff/src/printDiffs.ts index 984beb23f5c9..50a48c26c6c1 100644 --- a/packages/jest-diff/src/printDiffs.ts +++ b/packages/jest-diff/src/printDiffs.ts @@ -102,7 +102,10 @@ export const printCommonLine = ( emptyFirstOrLastLinePlaceholder, ); -export const hasCommonDiff = (diffs: Array, isMultiline: boolean) => { +export const hasCommonDiff = ( + diffs: Array, + isMultiline: boolean, +): boolean => { if (isMultiline) { // Important: Ignore common newline that was appended to multiline strings! const iLast = diffs.length - 1; diff --git a/packages/jest-docblock/src/index.ts b/packages/jest-docblock/src/index.ts index de524156b658..c4d416c7817b 100644 --- a/packages/jest-docblock/src/index.ts +++ b/packages/jest-docblock/src/index.ts @@ -24,7 +24,7 @@ export function extract(contents: string): string { return match ? match[0].trimLeft() : ''; } -export function strip(contents: string) { +export function strip(contents: string): string { const match = contents.match(docblockRe); return match && match[0] ? contents.substring(match[0].length) : contents; } diff --git a/packages/jest-each/src/validation.ts b/packages/jest-each/src/validation.ts index 3f95f94c832c..ae10259bcd6c 100644 --- a/packages/jest-each/src/validation.ts +++ b/packages/jest-each/src/validation.ts @@ -15,7 +15,7 @@ type TemplateData = Global.TemplateData; const EXPECTED_COLOR = chalk.green; const RECEIVED_COLOR = chalk.red; -export const validateArrayTable = (table: any) => { +export const validateArrayTable = (table: unknown): void => { if (!Array.isArray(table)) { throw new Error( '`.each` must be called with an Array or Tagged Template Literal.\n\n' + @@ -53,7 +53,7 @@ const isEmptyString = (str: string | unknown) => export const validateTemplateTableHeadings = ( headings: Array, data: TemplateData, -) => { +): void => { const missingData = data.length % headings.length; if (missingData > 0) { diff --git a/packages/jest-fake-timers/src/FakeTimersLolex.ts b/packages/jest-fake-timers/src/FakeTimersLolex.ts index 816fdddafa6a..56a767f4cab5 100644 --- a/packages/jest-fake-timers/src/FakeTimersLolex.ts +++ b/packages/jest-fake-timers/src/FakeTimersLolex.ts @@ -37,29 +37,29 @@ export default class FakeTimers { this._lolex = lolexWithGlobal(global); } - clearAllTimers() { + clearAllTimers(): void { if (this._fakingTime) { this._clock.reset(); } } - dispose() { + dispose(): void { this.useRealTimers(); } - runAllTimers() { + runAllTimers(): void { if (this._checkFakeTimers()) { this._clock.runAll(); } } - runOnlyPendingTimers() { + runOnlyPendingTimers(): void { if (this._checkFakeTimers()) { this._clock.runToLast(); } } - advanceTimersToNextTimer(steps = 1) { + advanceTimersToNextTimer(steps = 1): void { if (this._checkFakeTimers()) { for (let i = steps; i > 0; i--) { this._clock.next(); @@ -73,27 +73,27 @@ export default class FakeTimers { } } - advanceTimersByTime(msToRun: number) { + advanceTimersByTime(msToRun: number): void { if (this._checkFakeTimers()) { this._clock.tick(msToRun); } } - runAllTicks() { + runAllTicks(): void { if (this._checkFakeTimers()) { // @ts-ignore this._clock.runMicrotasks(); } } - useRealTimers() { + useRealTimers(): void { if (this._fakingTime) { this._clock.uninstall(); this._fakingTime = false; } } - useFakeTimers() { + useFakeTimers(): void { if (!this._fakingTime) { const toFake = Object.keys(this._lolex.timers) as Array< keyof LolexWithContext['timers'] @@ -110,7 +110,7 @@ export default class FakeTimers { } } - reset() { + reset(): void { if (this._checkFakeTimers()) { const {now} = this._clock; this._clock.reset(); @@ -118,17 +118,17 @@ export default class FakeTimers { } } - setSystemTime(now?: number) { + setSystemTime(now?: number): void { if (this._checkFakeTimers()) { this._clock.setSystemTime(now); } } - getRealSystemTime() { + getRealSystemTime(): number { return Date.now(); } - getTimerCount() { + getTimerCount(): number { if (this._checkFakeTimers()) { return this._clock.countTimers(); } diff --git a/packages/jest-fake-timers/src/jestFakeTimers.ts b/packages/jest-fake-timers/src/jestFakeTimers.ts index 7d46df24c42f..a31f413d4ee8 100644 --- a/packages/jest-fake-timers/src/jestFakeTimers.ts +++ b/packages/jest-fake-timers/src/jestFakeTimers.ts @@ -95,17 +95,17 @@ export default class FakeTimers { this._createMocks(); } - clearAllTimers() { + clearAllTimers(): void { this._immediates = []; this._timers.clear(); } - dispose() { + dispose(): void { this._disposed = true; this.clearAllTimers(); } - reset() { + reset(): void { this._cancelledTicks = {}; this._now = 0; this._ticks = []; @@ -113,7 +113,7 @@ export default class FakeTimers { this._timers = new Map(); } - runAllTicks() { + runAllTicks(): void { this._checkFakeTimers(); // Only run a generous number of ticks and then bail. // This is just to help avoid recursive loops @@ -142,7 +142,7 @@ export default class FakeTimers { } } - runAllImmediates() { + runAllImmediates(): void { this._checkFakeTimers(); // Only run a generous number of immediates and then bail. let i; @@ -172,7 +172,7 @@ export default class FakeTimers { } } - runAllTimers() { + runAllTimers(): void { this._checkFakeTimers(); this.runAllTicks(); this.runAllImmediates(); @@ -212,7 +212,7 @@ export default class FakeTimers { } } - runOnlyPendingTimers() { + runOnlyPendingTimers(): void { // We need to hold the current shape of `this._timers` because existing // timers can add new ones to the map and hence would run more than necessary. // See https://github.com/facebook/jest/pull/4608 for details @@ -225,7 +225,7 @@ export default class FakeTimers { .forEach(([timerHandle]) => this._runTimerHandle(timerHandle)); } - advanceTimersToNextTimer(steps = 1) { + advanceTimersToNextTimer(steps = 1): void { if (steps < 1) { return; } @@ -242,7 +242,7 @@ export default class FakeTimers { } } - advanceTimersByTime(msToRun: number) { + advanceTimersByTime(msToRun: number): void { this._checkFakeTimers(); // Only run a generous number of timers and then bail. // This is just to help avoid recursive loops @@ -281,7 +281,7 @@ export default class FakeTimers { } } - runWithRealTimers(cb: Callback) { + runWithRealTimers(cb: Callback): void { const prevClearImmediate = this._global.clearImmediate; const prevClearInterval = this._global.clearInterval; const prevClearTimeout = this._global.clearTimeout; @@ -314,7 +314,7 @@ export default class FakeTimers { } } - useRealTimers() { + useRealTimers(): void { const global = this._global; setGlobal(global, 'clearImmediate', this._timerAPIs.clearImmediate); setGlobal(global, 'clearInterval', this._timerAPIs.clearInterval); @@ -326,7 +326,7 @@ export default class FakeTimers { global.process.nextTick = this._timerAPIs.nextTick; } - useFakeTimers() { + useFakeTimers(): void { this._createMocks(); const global = this._global; @@ -340,7 +340,7 @@ export default class FakeTimers { global.process.nextTick = this._fakeTimerAPIs.nextTick; } - getTimerCount() { + getTimerCount(): number { this._checkFakeTimers(); return this._timers.size + this._immediates.length + this._ticks.length; diff --git a/packages/jest-haste-map/src/ModuleMap.ts b/packages/jest-haste-map/src/ModuleMap.ts index 73c904332bf5..24fe02643155 100644 --- a/packages/jest-haste-map/src/ModuleMap.ts +++ b/packages/jest-haste-map/src/ModuleMap.ts @@ -121,7 +121,7 @@ export default class ModuleMap { return this.json; } - static fromJSON(serializableModuleMap: SerializableModuleMap) { + static fromJSON(serializableModuleMap: SerializableModuleMap): ModuleMap { return new ModuleMap({ duplicates: ModuleMap.mapFromArrayRecursive( serializableModuleMap.duplicates, @@ -207,7 +207,7 @@ export default class ModuleMap { ); } - static create(rootDir: Config.Path) { + static create(rootDir: Config.Path): ModuleMap { return new ModuleMap({ duplicates: new Map(), map: new Map(), diff --git a/packages/jest-jasmine2/src/isError.ts b/packages/jest-jasmine2/src/isError.ts index f2081a8fb801..fc8e90201385 100644 --- a/packages/jest-jasmine2/src/isError.ts +++ b/packages/jest-jasmine2/src/isError.ts @@ -7,7 +7,10 @@ import prettyFormat = require('pretty-format'); -export default function isError(potentialError: any) { +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export default function isError( + potentialError: any, +): {isError: boolean; message: string | null} { // duck-type Error, see #2549 const isError = potentialError !== null && diff --git a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts index 85e1975ba7d4..e35b2aff293b 100644 --- a/packages/jest-jasmine2/src/jasmineAsyncInstall.ts +++ b/packages/jest-jasmine2/src/jasmineAsyncInstall.ts @@ -175,7 +175,7 @@ function makeConcurrent( export default function jasmineAsyncInstall( globalConfig: Config.GlobalConfig, global: Global.Global, -) { +): void { const jasmine = global.jasmine as Jasmine; const mutex = throat(globalConfig.maxConcurrency); diff --git a/packages/jest-jasmine2/src/jestExpect.ts b/packages/jest-jasmine2/src/jestExpect.ts index e6d33d121192..39dd471f859c 100644 --- a/packages/jest-jasmine2/src/jestExpect.ts +++ b/packages/jest-jasmine2/src/jestExpect.ts @@ -26,7 +26,7 @@ type JasmineMatcher = { type JasmineMatchersObject = {[id: string]: JasmineMatcher}; -export default (config: {expand: boolean}) => { +export default (config: {expand: boolean}): void => { global.expect = expect; expect.setState({expand: config.expand}); expect.extend({ diff --git a/packages/jest-jasmine2/src/queueRunner.ts b/packages/jest-jasmine2/src/queueRunner.ts index f10f484c79a7..dae635009722 100644 --- a/packages/jest-jasmine2/src/queueRunner.ts +++ b/packages/jest-jasmine2/src/queueRunner.ts @@ -26,6 +26,8 @@ export type QueueableFn = { initError?: Error; }; +// har to type :( +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export default function queueRunner(options: Options) { const token = new PCancelable((onCancel: Function, resolve: Function) => { onCancel(resolve); diff --git a/packages/jest-jasmine2/src/reporter.ts b/packages/jest-jasmine2/src/reporter.ts index 7970c045a738..d218aaebd6dc 100644 --- a/packages/jest-jasmine2/src/reporter.ts +++ b/packages/jest-jasmine2/src/reporter.ts @@ -43,9 +43,9 @@ export default class Jasmine2Reporter implements Reporter { this._startTimes = new Map(); } - jasmineStarted(_runDetails: RunDetails) {} + jasmineStarted(_runDetails: RunDetails): void {} - specStarted(spec: SpecResult) { + specStarted(spec: SpecResult): void { this._startTimes.set(spec.id, Date.now()); } diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index 94d8ee2a08aa..30dd5559640a 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -10,6 +10,7 @@ import {Plugin} from 'pretty-format'; import {extractExpectedAssertionsErrors, getState, setState} from 'expect'; import { SnapshotState, + SnapshotStateType, addSerializer, buildSnapshotResolver, } from 'jest-snapshot'; @@ -89,7 +90,7 @@ export default ({ globalConfig, localRequire, testPath, -}: SetupOptions) => { +}: SetupOptions): SnapshotStateType => { // Jest tests snapshotSerializers in order preceding built-in serializers. // Therefore, add in reverse because the last added is the first tested. config.snapshotSerializers diff --git a/packages/jest-jasmine2/src/treeProcessor.ts b/packages/jest-jasmine2/src/treeProcessor.ts index db59f94b0b11..89447eb75355 100644 --- a/packages/jest-jasmine2/src/treeProcessor.ts +++ b/packages/jest-jasmine2/src/treeProcessor.ts @@ -25,7 +25,7 @@ export type TreeNode = { children?: Array; } & Pick; -export default function treeProcessor(options: Options) { +export default function treeProcessor(options: Options): void { const { nodeComplete, nodeStart, diff --git a/packages/jest-matcher-utils/src/Replaceable.ts b/packages/jest-matcher-utils/src/Replaceable.ts index 2d32879286b2..6d1e8a2776c1 100644 --- a/packages/jest-matcher-utils/src/Replaceable.ts +++ b/packages/jest-matcher-utils/src/Replaceable.ts @@ -11,6 +11,7 @@ const supportTypes = ['map', 'array', 'object']; type ReplaceableForEachCallBack = (value: any, key: any, object: any) => void; +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ export default class Replaceable { object: any; type: string; @@ -60,3 +61,4 @@ export default class Replaceable { } } } +/* eslint-enable */ diff --git a/packages/jest-matcher-utils/src/index.ts b/packages/jest-matcher-utils/src/index.ts index 708f16ba910d..ce0de43db9ef 100644 --- a/packages/jest-matcher-utils/src/index.ts +++ b/packages/jest-matcher-utils/src/index.ts @@ -115,16 +115,16 @@ export const highlightTrailingWhitespace = (text: string): string => const replaceTrailingSpaces = (text: string): string => text.replace(/\s+$/gm, spaces => SPACE_SYMBOL.repeat(spaces.length)); -export const printReceived = (object: unknown) => +export const printReceived = (object: unknown): string => RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); -export const printExpected = (value: unknown) => +export const printExpected = (value: unknown): string => EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); export const printWithType = ( name: string, // 'Expected' or 'Received' value: unknown, print: (value: unknown) => string, // printExpected or printReceived -) => { +): string => { const type = getType(value); const hasType = type !== 'null' && type !== 'undefined' @@ -138,7 +138,7 @@ export const ensureNoExpected = ( expected: unknown, matcherName: string, options?: MatcherHintOptions, -) => { +): void => { if (typeof expected !== 'undefined') { // Prepend maybe not only for backward compatibility. const matcherString = (options ? '' : '[.not]') + matcherName; @@ -161,7 +161,7 @@ export const ensureActualIsNumber = ( actual: unknown, matcherName: string, options?: MatcherHintOptions, -) => { +): void => { if (typeof actual !== 'number' && typeof actual !== 'bigint') { // Prepend maybe not only for backward compatibility. const matcherString = (options ? '' : '[.not]') + matcherName; @@ -182,7 +182,7 @@ export const ensureExpectedIsNumber = ( expected: unknown, matcherName: string, options?: MatcherHintOptions, -) => { +): void => { if (typeof expected !== 'number' && typeof expected !== 'bigint') { // Prepend maybe not only for backward compatibility. const matcherString = (options ? '' : '[.not]') + matcherName; @@ -204,7 +204,7 @@ export const ensureNumbers = ( expected: unknown, matcherName: string, options?: MatcherHintOptions, -) => { +): void => { ensureActualIsNumber(actual, matcherName, options); ensureExpectedIsNumber(expected, matcherName, options); }; @@ -213,7 +213,7 @@ export const ensureExpectedIsNonNegativeInteger = ( expected: unknown, matcherName: string, options?: MatcherHintOptions, -) => { +): void => { if ( typeof expected !== 'number' || !Number.isSafeInteger(expected) || @@ -465,10 +465,13 @@ function isAsymmetricMatcher(data: any): data is AsymmetricMatcher { return type === 'object' && typeof data.asymmetricMatch === 'function'; } -export const diff = (a: any, b: any, options?: DiffOptions): string | null => - shouldPrintDiff(a, b) ? diffDefault(a, b, options) : null; +export const diff = ( + a: unknown, + b: unknown, + options?: DiffOptions, +): string | null => (shouldPrintDiff(a, b) ? diffDefault(a, b, options) : null); -export const pluralize = (word: string, count: number) => +export const pluralize = (word: string, count: number): string => (NUMBERS[count] || count) + ' ' + word + (count === 1 ? '' : 's'); // To display lines of labeled values as two columns with monospace alignment: @@ -483,14 +486,15 @@ export const getLabelPrinter = (...strings: Array): PrintLabel => { (max, string) => (string.length > max ? string.length : max), 0, ); - return string => `${string}: ${' '.repeat(maxLength - string.length)}`; + return (string: string): string => + `${string}: ${' '.repeat(maxLength - string.length)}`; }; export const matcherErrorMessage = ( hint: string, // assertion returned from call to matcherHint generic: string, // condition which correct value must fulfill specific?: string, // incorrect value returned from call to printWithType -) => +): string => `${hint}\n\n${chalk.bold('Matcher error')}: ${generic}${ typeof specific === 'string' ? '\n\n' + specific : '' }`; @@ -503,7 +507,7 @@ export const matcherHint = ( received: string = 'received', expected: string = 'expected', options: MatcherHintOptions = {}, -) => { +): string => { const { comment = '', expectedColor = EXPECTED_COLOR, diff --git a/packages/jest-message-util/src/index.ts b/packages/jest-message-util/src/index.ts index 66cee3dbc6cc..f83136f197e0 100644 --- a/packages/jest-message-util/src/index.ts +++ b/packages/jest-message-util/src/index.ts @@ -101,7 +101,7 @@ export const formatExecError = ( options: StackTraceOptions, testPath?: Path, reuseMessage?: boolean, -) => { +): string => { if (!error || typeof error === 'number') { error = new Error(`Expected an Error, but "${String(error)}" was thrown`); error.stack = ''; @@ -227,7 +227,7 @@ const formatPaths = ( export const getStackTraceLines = ( stack: string, options: StackTraceOptions = {noStackTrace: false}, -) => removeInternalStackEntries(stack.split(/\n/), options); +): Array => removeInternalStackEntries(stack.split(/\n/), options); export const getTopFrame = (lines: Array): Frame | null => { for (const line of lines) { @@ -250,7 +250,7 @@ export const formatStackTrace = ( config: StackTraceConfig, options: StackTraceOptions, testPath?: Path, -) => { +): string => { const lines = getStackTraceLines(stack, options); const topFrame = getTopFrame(lines); let renderedCallsite = ''; @@ -343,7 +343,9 @@ const removeBlankErrorLine = (str: string) => // jasmine and worker farm sometimes don't give us access to the actual // Error object, so we have to regexp out the message from the stack string // to format it. -export const separateMessageFromStack = (content: string) => { +export const separateMessageFromStack = ( + content: string, +): {message: string; stack: string} => { if (!content) { return {message: '', stack: ''}; } diff --git a/packages/jest-regex-util/src/index.ts b/packages/jest-regex-util/src/index.ts index c63605d972b2..bac9a5b4c325 100644 --- a/packages/jest-regex-util/src/index.ts +++ b/packages/jest-regex-util/src/index.ts @@ -8,7 +8,7 @@ import {sep} from 'path'; -export const escapePathForRegex = (dir: string) => { +export const escapePathForRegex = (dir: string): string => { if (sep === '\\') { // Replace "\" with "/" so it's not escaped by escapeStrForRegex. // replacePathSepForRegex will convert it back. @@ -17,10 +17,10 @@ export const escapePathForRegex = (dir: string) => { return replacePathSepForRegex(escapeStrForRegex(dir)); }; -export const escapeStrForRegex = (string: string) => +export const escapeStrForRegex = (string: string): string => string.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&'); -export const replacePathSepForRegex = (string: string) => { +export const replacePathSepForRegex = (string: string): string => { if (sep === '\\') { return string.replace( /(\/|(.)?\\(?![[\]{}()*+?.^$|\\]))/g, diff --git a/packages/jest-reporters/src/Status.ts b/packages/jest-reporters/src/Status.ts index efd927aa7e1c..010059230f90 100644 --- a/packages/jest-reporters/src/Status.ts +++ b/packages/jest-reporters/src/Status.ts @@ -57,13 +57,18 @@ class CurrentTestList { } } +type Cache = { + content: string; + clear: string; +}; + /** * A class that generates the CLI status of currently running tests * and also provides an ANSI escape sequence to remove status lines * from the terminal. */ export default class Status { - private _cache: {content: string; clear: string} | null; + private _cache: Cache | null; private _callback?: () => void; private _currentTests: CurrentTestList; private _done: boolean; @@ -82,14 +87,14 @@ export default class Status { this._showStatus = false; } - onChange(callback: () => void) { + onChange(callback: () => void): void { this._callback = callback; } runStarted( aggregatedResults: AggregatedResult, options: ReporterOnStartOptions, - ) { + ): void { this._estimatedTime = (options && options.estimatedTime) || 0; this._showStatus = options && options.showStatus; this._interval = setInterval(() => this._tick(), 1000); @@ -97,13 +102,13 @@ export default class Status { this._debouncedEmit(); } - runFinished() { + runFinished(): void { this._done = true; if (this._interval) clearInterval(this._interval); this._emit(); } - testStarted(testPath: Config.Path, config: Config.ProjectConfig) { + testStarted(testPath: Config.Path, config: Config.ProjectConfig): void { this._currentTests.add(testPath, config); if (!this._showStatus) { this._emit(); @@ -116,14 +121,14 @@ export default class Status { _config: Config.ProjectConfig, testResult: TestResult, aggregatedResults: AggregatedResult, - ) { + ): void { const {testFilePath} = testResult; this._aggregatedResults = aggregatedResults; this._currentTests.delete(testFilePath); this._debouncedEmit(); } - get() { + get(): Cache { if (this._cache) { return this._cache; } diff --git a/packages/jest-reporters/src/base_reporter.ts b/packages/jest-reporters/src/base_reporter.ts index 0d094c7f0de3..7f995f608976 100644 --- a/packages/jest-reporters/src/base_reporter.ts +++ b/packages/jest-reporters/src/base_reporter.ts @@ -14,11 +14,14 @@ const {remove: preRunMessageRemove} = preRunMessage; export default class BaseReporter implements Reporter { private _error?: Error; - log(message: string) { + log(message: string): void { process.stderr.write(message + '\n'); } - onRunStart(_results?: AggregatedResult, _options?: ReporterOnStartOptions) { + onRunStart( + _results?: AggregatedResult, + _options?: ReporterOnStartOptions, + ): void { preRunMessageRemove(process.stderr); } @@ -26,22 +29,22 @@ export default class BaseReporter implements Reporter { _test?: Test, _testResult?: TestResult, _results?: AggregatedResult, - ) {} + ): void {} - onTestStart(_test?: Test) {} + onTestStart(_test?: Test): void {} onRunComplete( _contexts?: Set, _aggregatedResults?: AggregatedResult, ): Promise | void {} - protected _setError(error: Error) { + protected _setError(error: Error): void { this._error = error; } // Return an error that occurred during reporting. This error will // define whether the test run was successful or failed. - getLastError() { + getLastError(): Error | undefined { return this._error; } } diff --git a/packages/jest-reporters/src/coverage_reporter.ts b/packages/jest-reporters/src/coverage_reporter.ts index d088af38c8b8..1da07f073b76 100644 --- a/packages/jest-reporters/src/coverage_reporter.ts +++ b/packages/jest-reporters/src/coverage_reporter.ts @@ -57,7 +57,7 @@ export default class CoverageReporter extends BaseReporter { this._options = options || {}; } - onTestResult(_test: Test, testResult: TestResult) { + onTestResult(_test: Test, testResult: TestResult): void { if (testResult.v8Coverage) { this._v8CoverageResults.push(testResult.v8Coverage); return; @@ -93,7 +93,7 @@ export default class CoverageReporter extends BaseReporter { async onRunComplete( contexts: Set, aggregatedResults: AggregatedResult, - ) { + ): Promise { await this._addUntestedFiles(contexts); const {map, reportContext} = await this._getCoverageResult(); diff --git a/packages/jest-reporters/src/default_reporter.ts b/packages/jest-reporters/src/default_reporter.ts index 982236fde3e2..04543ef73563 100644 --- a/packages/jest-reporters/src/default_reporter.ts +++ b/packages/jest-reporters/src/default_reporter.ts @@ -91,7 +91,7 @@ export default class DefaultReporter extends BaseReporter { } // Don't wait for the debounced call and flush all output immediately. - forceFlushBufferedOutput() { + forceFlushBufferedOutput(): void { for (const flushBufferedOutput of this._bufferedOutput) { flushBufferedOutput(); } @@ -122,15 +122,15 @@ export default class DefaultReporter extends BaseReporter { onRunStart( aggregatedResults: AggregatedResult, options: ReporterOnStartOptions, - ) { + ): void { this._status.runStarted(aggregatedResults, options); } - onTestStart(test: Test) { + onTestStart(test: Test): void { this._status.testStarted(test.path, test.context.config); } - onRunComplete() { + onRunComplete(): void { this.forceFlushBufferedOutput(); this._status.runFinished(); process.stdout.write = this._out; @@ -142,7 +142,7 @@ export default class DefaultReporter extends BaseReporter { test: Test, testResult: TestResult, aggregatedResults: AggregatedResult, - ) { + ): void { this.testFinished(test.context.config, testResult, aggregatedResults); if (!testResult.skipped) { this.printTestFileHeader( @@ -163,7 +163,7 @@ export default class DefaultReporter extends BaseReporter { config: Config.ProjectConfig, testResult: TestResult, aggregatedResults: AggregatedResult, - ) { + ): void { this._status.testFinished(config, testResult, aggregatedResults); } @@ -171,7 +171,7 @@ export default class DefaultReporter extends BaseReporter { _testPath: Config.Path, config: Config.ProjectConfig, result: TestResult, - ) { + ): void { this.log(getResultHeader(result, this._globalConfig, config)); if (result.console) { this.log( @@ -191,7 +191,7 @@ export default class DefaultReporter extends BaseReporter { _testPath: Config.Path, _config: Config.ProjectConfig, result: TestResult, - ) { + ): void { if (result.failureMessage) { this.log(result.failureMessage); } diff --git a/packages/jest-reporters/src/get_result_header.ts b/packages/jest-reporters/src/get_result_header.ts index 827b7f84833d..66485e065f25 100644 --- a/packages/jest-reporters/src/get_result_header.ts +++ b/packages/jest-reporters/src/get_result_header.ts @@ -29,7 +29,7 @@ export default ( result: TestResult, globalConfig: Config.GlobalConfig, projectConfig?: Config.ProjectConfig, -) => { +): string => { const testPath = result.testFilePath; const formattedTestPath = formatTestPath( projectConfig ? projectConfig : globalConfig, diff --git a/packages/jest-reporters/src/summary_reporter.ts b/packages/jest-reporters/src/summary_reporter.ts index a92f4fdf4d78..026e29bbac55 100644 --- a/packages/jest-reporters/src/summary_reporter.ts +++ b/packages/jest-reporters/src/summary_reporter.ts @@ -74,12 +74,15 @@ export default class SummaryReporter extends BaseReporter { onRunStart( aggregatedResults: AggregatedResult, options: ReporterOnStartOptions, - ) { + ): void { super.onRunStart(aggregatedResults, options); this._estimatedTime = options.estimatedTime; } - onRunComplete(contexts: Set, aggregatedResults: AggregatedResult) { + onRunComplete( + contexts: Set, + aggregatedResults: AggregatedResult, + ): void { const {numTotalTestSuites, testResults, wasInterrupted} = aggregatedResults; if (numTotalTestSuites) { const lastResult = testResults[testResults.length - 1]; diff --git a/packages/jest-reporters/src/utils.ts b/packages/jest-reporters/src/utils.ts index 97781b8ef8ac..2e201aa605de 100644 --- a/packages/jest-reporters/src/utils.ts +++ b/packages/jest-reporters/src/utils.ts @@ -15,7 +15,7 @@ import {SummaryOptions} from './types'; const PROGRESS_BAR_WIDTH = 40; -export const printDisplayName = (config: Config.ProjectConfig) => { +export const printDisplayName = (config: Config.ProjectConfig): string => { const {displayName} = config; const white = chalk.reset.inverse.white; if (!displayName) { @@ -73,7 +73,7 @@ export const trimAndFormatPath = ( export const formatTestPath = ( config: Config.GlobalConfig | Config.ProjectConfig, testPath: Config.Path, -) => { +): string => { const {dirname, basename} = relativePath(config, testPath); return slash(chalk.dim(dirname + path.sep) + chalk.bold(basename)); }; @@ -81,7 +81,7 @@ export const formatTestPath = ( export const relativePath = ( config: Config.GlobalConfig | Config.ProjectConfig, testPath: Config.Path, -) => { +): {basename: string; dirname: string} => { // this function can be called with ProjectConfigs or GlobalConfigs. GlobalConfigs // do not have config.cwd, only config.rootDir. Try using config.cwd, fallback // to config.rootDir. (Also, some unit just use config.rootDir, which is ok) @@ -97,7 +97,7 @@ export const relativePath = ( export const getSummary = ( aggregatedResults: AggregatedResult, options?: SummaryOptions, -) => { +): string => { let runTime = (Date.now() - aggregatedResults.startTime) / 1000; if (options && options.roundTime) { runTime = Math.floor(runTime); @@ -212,7 +212,10 @@ const renderTime = (runTime: number, estimatedTime: number, width: number) => { // word-wrap a string that contains ANSI escape sequences. // ANSI escape sequences do not add to the string length. -export const wrapAnsiString = (string: string, terminalWidth: number) => { +export const wrapAnsiString = ( + string: string, + terminalWidth: number, +): string => { if (terminalWidth === 0) { // if the terminal width is zero, don't bother word-wrapping return string; diff --git a/packages/jest-reporters/src/verbose_reporter.ts b/packages/jest-reporters/src/verbose_reporter.ts index 4fd78dd6da1f..6f05e4a2d82a 100644 --- a/packages/jest-reporters/src/verbose_reporter.ts +++ b/packages/jest-reporters/src/verbose_reporter.ts @@ -33,7 +33,7 @@ export default class VerboseReporter extends DefaultReporter { return testResults.filter(({status}) => status !== 'pending'); } - static groupTestsBySuites(testResults: Array) { + static groupTestsBySuites(testResults: Array): Suite { const root: Suite = {suites: [], tests: [], title: ''}; testResults.forEach(testResult => { let targetSuite = root; @@ -58,7 +58,7 @@ export default class VerboseReporter extends DefaultReporter { test: Test, result: TestResult, aggregatedResults: AggregatedResult, - ) { + ): void { super.testFinished(test.context.config, result, aggregatedResults); if (!result.skipped) { this.printTestFileHeader( @@ -144,7 +144,7 @@ export default class VerboseReporter extends DefaultReporter { } private _logTodoOrPendingTest(indentLevel: number) { - return (test: AssertionResult) => { + return (test: AssertionResult): void => { const printedTestStatus = test.status === 'pending' ? 'skipped' : test.status; const icon = this._getIcon(test.status); diff --git a/packages/jest-resolve/src/defaultResolver.ts b/packages/jest-resolve/src/defaultResolver.ts index cf9c28ec9bc6..03503e7d3d01 100644 --- a/packages/jest-resolve/src/defaultResolver.ts +++ b/packages/jest-resolve/src/defaultResolver.ts @@ -58,7 +58,7 @@ export default function defaultResolver( return result; } -export function clearDefaultResolverCache() { +export function clearDefaultResolverCache(): void { checkedPaths.clear(); } @@ -68,7 +68,7 @@ enum IPathType { OTHER = 3, } const checkedPaths = new Map(); -function statSyncCached(path: string): number { +function statSyncCached(path: string): IPathType { const result = checkedPaths.get(path); if (result !== undefined) { return result; diff --git a/packages/jest-runner/src/testWorker.ts b/packages/jest-runner/src/testWorker.ts index 9987c7ee3f30..2de4d81fdeef 100644 --- a/packages/jest-runner/src/testWorker.ts +++ b/packages/jest-runner/src/testWorker.ts @@ -63,7 +63,7 @@ const getResolver = (config: Config.ProjectConfig) => { export function setup(setupData: { serializableResolvers: Array; -}) { +}): void { // Module maps that will be needed for the test runs are passed. for (const { config, diff --git a/packages/jest-runtime/src/cli/index.ts b/packages/jest-runtime/src/cli/index.ts index 3d1a9ddd2b03..1da49004242a 100644 --- a/packages/jest-runtime/src/cli/index.ts +++ b/packages/jest-runtime/src/cli/index.ts @@ -20,7 +20,10 @@ import {VERSION} from '../version'; import {Context} from '../types'; import * as args from './args'; -export async function run(cliArgv?: Config.Argv, cliInfo?: Array) { +export async function run( + cliArgv?: Config.Argv, + cliInfo?: Array, +): Promise { const realFs = require('fs'); const fs = require('graceful-fs'); fs.gracefulify(realFs); diff --git a/packages/jest-serializer/src/index.ts b/packages/jest-serializer/src/index.ts index 1a3d3c28a4bf..4483f5b45f7d 100644 --- a/packages/jest-serializer/src/index.ts +++ b/packages/jest-serializer/src/index.ts @@ -33,7 +33,7 @@ export function readFileSync(filePath: Path): any { return v8Deserialize(fs.readFileSync(filePath)); } -export function writeFileSync(filePath: Path, content: any) { +export function writeFileSync(filePath: Path, content: unknown): void { return fs.writeFileSync(filePath, v8Serialize(content)); } diff --git a/packages/jest-snapshot/package.json b/packages/jest-snapshot/package.json index d2f9027e4a25..0f5f9c84c74b 100644 --- a/packages/jest-snapshot/package.json +++ b/packages/jest-snapshot/package.json @@ -12,6 +12,7 @@ "dependencies": { "@babel/types": "^7.0.0", "@jest/types": "^25.1.0", + "@types/prettier": "^1.19.0", "chalk": "^3.0.0", "expect": "^25.1.0", "jest-diff": "^25.1.0", @@ -27,7 +28,6 @@ "devDependencies": { "@babel/traverse": "^7.3.4", "@types/natural-compare": "^1.4.0", - "@types/prettier": "^1.16.1", "@types/semver": "^6.0.1", "jest-haste-map": "^25.1.0", "prettier": "^1.13.4" diff --git a/packages/jest-snapshot/src/State.ts b/packages/jest-snapshot/src/State.ts index da0ee884a8db..0a569fbd41c0 100644 --- a/packages/jest-snapshot/src/State.ts +++ b/packages/jest-snapshot/src/State.ts @@ -24,7 +24,7 @@ import {SnapshotData} from './types'; export type SnapshotStateOptions = { updateSnapshot: Config.SnapshotUpdateState; - getPrettier: () => null | any; + getPrettier: () => null | typeof import('prettier'); getBabelTraverse: () => Function; expand?: boolean; }; @@ -46,6 +46,11 @@ type SnapshotReturnOptions = { pass: boolean; }; +type SaveStatus = { + deleted: boolean; + saved: boolean; +}; + export default class SnapshotState { private _counters: Map; private _dirty: boolean; @@ -58,7 +63,7 @@ export default class SnapshotState { private _inlineSnapshots: Array; private _uncheckedKeys: Set; private _getBabelTraverse: () => Function; - private _getPrettier: () => null | any; + private _getPrettier: () => null | typeof import('prettier'); added: number; expand: boolean; @@ -89,7 +94,7 @@ export default class SnapshotState { this.updated = 0; } - markSnapshotsAsCheckedForTest(testName: string) { + markSnapshotsAsCheckedForTest(testName: string): void { this._uncheckedKeys.forEach(uncheckedKey => { if (keyToTestName(uncheckedKey) === testName) { this._uncheckedKeys.delete(uncheckedKey); @@ -101,7 +106,7 @@ export default class SnapshotState { key: string, receivedSerialized: string, options: {isInline: boolean; error?: Error}, - ) { + ): void { this._dirty = true; if (options.isInline) { const error = options.error || new Error(); @@ -123,7 +128,7 @@ export default class SnapshotState { } } - clear() { + clear(): void { this._snapshotData = this._initialData; this._inlineSnapshots = []; this._counters = new Map(); @@ -134,12 +139,12 @@ export default class SnapshotState { this.updated = 0; } - save() { + save(): SaveStatus { const hasExternalSnapshots = Object.keys(this._snapshotData).length; const hasInlineSnapshots = this._inlineSnapshots.length; const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots; - const status = { + const status: SaveStatus = { deleted: false, saved: false, }; @@ -279,7 +284,7 @@ export default class SnapshotState { } } - fail(testName: string, _received: any, key?: string) { + fail(testName: string, _received: unknown, key?: string): string { this._counters.set(testName, (this._counters.get(testName) || 0) + 1); const count = Number(this._counters.get(testName)); diff --git a/packages/jest-snapshot/src/inline_snapshots.ts b/packages/jest-snapshot/src/inline_snapshots.ts index 872a024608da..3321e23fb2b5 100644 --- a/packages/jest-snapshot/src/inline_snapshots.ts +++ b/packages/jest-snapshot/src/inline_snapshots.ts @@ -26,9 +26,9 @@ export type InlineSnapshot = { export const saveInlineSnapshots = ( snapshots: Array, - prettier: any, + prettier: typeof import('prettier') | null, babelTraverse: Function, -) => { +): void => { if (!prettier) { throw new Error( `Jest: Inline Snapshots requires Prettier.\n` + diff --git a/packages/jest-snapshot/src/plugins.ts b/packages/jest-snapshot/src/plugins.ts index c794fbcc8265..579c638a84cd 100644 --- a/packages/jest-snapshot/src/plugins.ts +++ b/packages/jest-snapshot/src/plugins.ts @@ -29,8 +29,8 @@ let PLUGINS: prettyFormat.Plugins = [ ]; // Prepend to list so the last added is the first tested. -export const addSerializer = (plugin: prettyFormat.Plugin) => { +export const addSerializer = (plugin: prettyFormat.Plugin): void => { PLUGINS = [plugin].concat(PLUGINS); }; -export const getSerializers = () => PLUGINS; +export const getSerializers = (): prettyFormat.Plugins => PLUGINS; diff --git a/packages/jest-snapshot/src/printSnapshot.ts b/packages/jest-snapshot/src/printSnapshot.ts index 72048c9e0f66..af52e8166fc1 100644 --- a/packages/jest-snapshot/src/printSnapshot.ts +++ b/packages/jest-snapshot/src/printSnapshot.ts @@ -88,7 +88,7 @@ export const getReceivedColorForChalkInstance = ( export const aSnapshotColor = getSnapshotColorForChalkInstance(chalk); export const bReceivedColor = getReceivedColorForChalkInstance(chalk); -export const noColor = (string: string) => string; +export const noColor = (string: string): string => string; export const HINT_ARG = 'hint'; export const SNAPSHOT_ARG = 'snapshot'; @@ -195,8 +195,10 @@ const isLineDiffable = (received: any): boolean => { return true; }; -export const printExpected = (val: unknown) => EXPECTED_COLOR(minify(val)); -export const printReceived = (val: unknown) => RECEIVED_COLOR(minify(val)); +export const printExpected = (val: unknown): string => + EXPECTED_COLOR(minify(val)); +export const printReceived = (val: unknown): string => + RECEIVED_COLOR(minify(val)); export const printPropertiesAndReceived = ( properties: object, diff --git a/packages/jest-snapshot/src/utils.ts b/packages/jest-snapshot/src/utils.ts index fbdaf73a1370..b2497b007752 100644 --- a/packages/jest-snapshot/src/utils.ts +++ b/packages/jest-snapshot/src/utils.ts @@ -181,7 +181,7 @@ export const escapeBacktickString = (str: string): string => const printBacktickString = (str: string): string => '`' + escapeBacktickString(str) + '`'; -export const ensureDirectoryExists = (filePath: Config.Path) => { +export const ensureDirectoryExists = (filePath: Config.Path): void => { try { makeDir.sync(path.join(path.dirname(filePath))); } catch (e) {} @@ -192,7 +192,7 @@ const normalizeNewlines = (string: string) => string.replace(/\r\n|\r/g, '\n'); export const saveSnapshotFile = ( snapshotData: SnapshotData, snapshotPath: Config.Path, -) => { +): void => { const snapshots = Object.keys(snapshotData) .sort(naturalCompare) .map( @@ -230,7 +230,8 @@ const deepMergeArray = (target: Array, source: Array) => { return mergedOutput; }; -export const deepMerge = (target: any, source: any) => { +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export const deepMerge = (target: any, source: any): any => { const mergedOutput = {...target}; if (isObject(target) && isObject(source)) { Object.keys(source).forEach(key => { diff --git a/packages/jest-source-map/src/getCallsite.ts b/packages/jest-source-map/src/getCallsite.ts index 6a3c8fa512a3..ba8792015db2 100644 --- a/packages/jest-source-map/src/getCallsite.ts +++ b/packages/jest-source-map/src/getCallsite.ts @@ -46,7 +46,10 @@ const addSourceMapConsumer = ( }); }; -export default (level: number, sourceMaps?: SourceMapRegistry | null) => { +export default ( + level: number, + sourceMaps?: SourceMapRegistry | null, +): callsites.CallSite => { const levelAfterThisCall = level + 1; const stack = callsites()[levelAfterThisCall]; const sourceMapFileName = sourceMaps && sourceMaps[stack.getFileName() || '']; diff --git a/packages/jest-test-sequencer/src/index.ts b/packages/jest-test-sequencer/src/index.ts index 4098be5d0edf..3275e8566739 100644 --- a/packages/jest-test-sequencer/src/index.ts +++ b/packages/jest-test-sequencer/src/index.ts @@ -34,12 +34,12 @@ type Cache = { export default class TestSequencer { private _cache: Map = new Map(); - _getCachePath(context: Context) { + _getCachePath(context: Context): string { const {config} = context; return getCacheFilePath(config.cacheDirectory, 'perf-cache-' + config.name); } - _getCache(test: Test) { + _getCache(test: Test): Cache { const {context} = test; if (!this._cache.has(context) && context.config.cache) { const cachePath = this._getCachePath(context); @@ -109,7 +109,7 @@ export default class TestSequencer { }); } - cacheResults(tests: Array, results: AggregatedResult) { + cacheResults(tests: Array, results: AggregatedResult): void { const map = Object.create(null); tests.forEach(test => (map[test.path] = test)); results.testResults.forEach(testResult => { diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index 643e7387ddf2..8d6a06637be7 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -250,7 +250,11 @@ export default class ScriptTransformer { this._getTransformer(filepath); } - transformSource(filepath: Config.Path, content: string, instrument: boolean) { + transformSource( + filepath: Config.Path, + content: string, + instrument: boolean, + ): TransformResult { const filename = this._getRealPath(filepath); const transform = this._getTransformer(filename); const cacheFilePath = this._getFileCachePath(filename, content, instrument); @@ -277,6 +281,7 @@ export default class ScriptTransformer { return { code, mapCoverage, + originalCode: content, sourceMapPath, }; } @@ -362,6 +367,7 @@ export default class ScriptTransformer { return { code, mapCoverage, + originalCode: content, sourceMapPath, }; } @@ -545,7 +551,13 @@ export default class ScriptTransformer { } } -export function createTranspilingRequire(config: Config.ProjectConfig) { +// TODO: do we need to define the generics twice? +export function createTranspilingRequire( + config: Config.ProjectConfig, +): ( + resolverPath: string, + applyInteropRequireDefault?: boolean, +) => TModuleType { const transformer = new ScriptTransformer(config); return function requireAndTranspileModule( diff --git a/packages/jest-transform/src/enhanceUnexpectedTokenMessage.ts b/packages/jest-transform/src/enhanceUnexpectedTokenMessage.ts index d5e3b60111bb..327d27cc405f 100644 --- a/packages/jest-transform/src/enhanceUnexpectedTokenMessage.ts +++ b/packages/jest-transform/src/enhanceUnexpectedTokenMessage.ts @@ -9,9 +9,13 @@ import chalk = require('chalk'); const DOT = ' \u2022 '; +interface ErrorWithCodeFrame extends Error { + codeFrame?: string; +} + export default function handlePotentialSyntaxError( - e: Error & {codeFrame?: string}, -) { + e: ErrorWithCodeFrame, +): ErrorWithCodeFrame { if (e.codeFrame) { e.stack = e.message + '\n' + e.codeFrame; } @@ -29,7 +33,7 @@ export default function handlePotentialSyntaxError( return e; } -export function enhanceUnexpectedTokenMessage(e: Error) { +export function enhanceUnexpectedTokenMessage(e: Error): Error { e.stack = `${chalk.bold.red('Jest encountered an unexpected token')} diff --git a/packages/jest-util/src/clearLine.ts b/packages/jest-util/src/clearLine.ts index dcf770c9624f..24431d45174d 100644 --- a/packages/jest-util/src/clearLine.ts +++ b/packages/jest-util/src/clearLine.ts @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -export default function clearLine(stream: NodeJS.WriteStream) { +export default function clearLine(stream: NodeJS.WriteStream): void { if (stream.isTTY) { stream.write('\x1b[999D\x1b[K'); } diff --git a/packages/jest-util/src/createDirectory.ts b/packages/jest-util/src/createDirectory.ts index b761f44c9ffb..6a9acac2029b 100644 --- a/packages/jest-util/src/createDirectory.ts +++ b/packages/jest-util/src/createDirectory.ts @@ -8,7 +8,7 @@ import makeDir = require('make-dir'); import {Config} from '@jest/types'; -export default function createDirectory(path: Config.Path) { +export default function createDirectory(path: Config.Path): void { try { makeDir.sync(path); } catch (e) { diff --git a/packages/jest-util/src/createProcessObject.ts b/packages/jest-util/src/createProcessObject.ts index ebd2d1a7cb61..621754380072 100644 --- a/packages/jest-util/src/createProcessObject.ts +++ b/packages/jest-util/src/createProcessObject.ts @@ -79,7 +79,7 @@ function createProcessEnv(): NodeJS.ProcessEnv { return Object.assign(proxy, process.env); } -export default function() { +export default function(): NodeJS.Process { const process = require('process'); const newProcess = deepCyclicCopy(process, { blacklist: BLACKLIST, diff --git a/packages/jest-util/src/interopRequireDefault.ts b/packages/jest-util/src/interopRequireDefault.ts index 471433dcca0f..535f8ec73fa8 100644 --- a/packages/jest-util/src/interopRequireDefault.ts +++ b/packages/jest-util/src/interopRequireDefault.ts @@ -6,6 +6,7 @@ */ // copied from https://github.com/babel/babel/blob/56044c7851d583d498f919e9546caddf8f80a72f/packages/babel-helpers/src/helpers.js#L558-L562 -export default function interopRequireDefault(obj: any) { +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export default function interopRequireDefault(obj: any): any { return obj && obj.__esModule ? obj : {default: obj}; } diff --git a/packages/jest-util/src/pluralize.ts b/packages/jest-util/src/pluralize.ts index 95f29391cc5a..1c283665fbad 100644 --- a/packages/jest-util/src/pluralize.ts +++ b/packages/jest-util/src/pluralize.ts @@ -5,6 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -export default function pluralize(word: string, count: number) { +export default function pluralize(word: string, count: number): string { return `${count} ${word}${count === 1 ? '' : 's'}`; } diff --git a/packages/jest-util/src/preRunMessage.ts b/packages/jest-util/src/preRunMessage.ts index 5f60c71f26d9..cb011452c271 100644 --- a/packages/jest-util/src/preRunMessage.ts +++ b/packages/jest-util/src/preRunMessage.ts @@ -9,13 +9,13 @@ import chalk = require('chalk'); import clearLine from './clearLine'; import isInteractive from './isInteractive'; -export const print = (stream: NodeJS.WriteStream) => { +export const print = (stream: NodeJS.WriteStream): void => { if (isInteractive) { stream.write(chalk.bold.dim('Determining test suites to run...')); } }; -export const remove = (stream: NodeJS.WriteStream) => { +export const remove = (stream: NodeJS.WriteStream): void => { if (isInteractive) { clearLine(stream); } diff --git a/packages/jest-util/src/setGlobal.ts b/packages/jest-util/src/setGlobal.ts index e7eb341f05a0..012b3bd721ae 100644 --- a/packages/jest-util/src/setGlobal.ts +++ b/packages/jest-util/src/setGlobal.ts @@ -9,7 +9,7 @@ export default ( globalToMutate: NodeJS.Global | Window, key: string, value: unknown, -) => { +): void => { // @ts-ignore: no index globalToMutate[key] = value; }; diff --git a/packages/jest-util/src/testPathPatternToRegExp.ts b/packages/jest-util/src/testPathPatternToRegExp.ts index c64f8d2af7da..6149c83b90b8 100644 --- a/packages/jest-util/src/testPathPatternToRegExp.ts +++ b/packages/jest-util/src/testPathPatternToRegExp.ts @@ -10,5 +10,6 @@ import {Config} from '@jest/types'; // Because we serialize/deserialize globalConfig when we spawn workers, // we can't pass regular expression. Using this shared function on both sides // will ensure that we produce consistent regexp for testPathPattern. -export default (testPathPattern: Config.GlobalConfig['testPathPattern']) => - new RegExp(testPathPattern, 'i'); +export default ( + testPathPattern: Config.GlobalConfig['testPathPattern'], +): RegExp => new RegExp(testPathPattern, 'i'); diff --git a/packages/jest-validate/src/condition.ts b/packages/jest-validate/src/condition.ts index c413e631d388..b8bb69c763b6 100644 --- a/packages/jest-validate/src/condition.ts +++ b/packages/jest-validate/src/condition.ts @@ -9,7 +9,10 @@ const toString = Object.prototype.toString; const MULTIPLE_VALID_OPTIONS_SYMBOL = Symbol('JEST_MULTIPLE_VALID_OPTIONS'); -function validationConditionSingle(option: any, validOption: any): boolean { +function validationConditionSingle( + option: unknown, + validOption: unknown, +): boolean { return ( option === null || option === undefined || @@ -18,7 +21,7 @@ function validationConditionSingle(option: any, validOption: any): boolean { ); } -export function getValues(validOption: any) { +export function getValues(validOption: T): Array { if ( Array.isArray(validOption) && // @ts-ignore @@ -29,7 +32,10 @@ export function getValues(validOption: any) { return [validOption]; } -export function validationCondition(option: any, validOption: any): boolean { +export function validationCondition( + option: unknown, + validOption: unknown, +): boolean { return getValues(validOption).some(e => validationConditionSingle(option, e)); } @@ -39,5 +45,6 @@ export function multipleValidOptions>( const options = [...args]; // @ts-ignore options[MULTIPLE_VALID_OPTIONS_SYMBOL] = true; + return options; } diff --git a/packages/jest-validate/src/errors.ts b/packages/jest-validate/src/errors.ts index d80d8a721ec6..cb3ac6f107f9 100644 --- a/packages/jest-validate/src/errors.ts +++ b/packages/jest-validate/src/errors.ts @@ -13,8 +13,8 @@ import {ValidationOptions} from './types'; export const errorMessage = ( option: string, - received: any, - defaultValue: any, + received: unknown, + defaultValue: unknown, options: ValidationOptions, path?: Array, ): void => { diff --git a/packages/jest-validate/src/utils.ts b/packages/jest-validate/src/utils.ts index 7c2cc5c721dc..d2414dd50d1a 100644 --- a/packages/jest-validate/src/utils.ts +++ b/packages/jest-validate/src/utils.ts @@ -14,12 +14,12 @@ export const DEPRECATION = `${BULLET} Deprecation Warning`; export const ERROR = `${BULLET} Validation Error`; export const WARNING = `${BULLET} Validation Warning`; -export const format = (value: any): string => +export const format = (value: unknown): string => typeof value === 'function' ? value.toString() : prettyFormat(value, {min: true}); -export const formatPrettyObject = (value: any): string => +export const formatPrettyObject = (value: unknown): string => typeof value === 'function' ? value.toString() : JSON.stringify(value, null, 2) @@ -43,7 +43,7 @@ export const logValidationWarning = ( name: string, message: string, comment?: string | null, -) => { +): void => { comment = comment ? '\n\n' + comment : '\n'; console.warn(chalk.yellow(chalk.bold(name) + ':\n\n' + message + comment)); }; @@ -51,7 +51,7 @@ export const logValidationWarning = ( export const createDidYouMeanMessage = ( unrecognized: string, allowedOptions: Array, -) => { +): string => { const suggestion = allowedOptions.find(option => { const steps: number = leven(option, unrecognized); return steps < 3; diff --git a/packages/jest-validate/src/validateCLIOptions.ts b/packages/jest-validate/src/validateCLIOptions.ts index a1353b90407a..b13ad4fb8482 100644 --- a/packages/jest-validate/src/validateCLIOptions.ts +++ b/packages/jest-validate/src/validateCLIOptions.ts @@ -69,7 +69,7 @@ export default function validateCLIOptions( [s: string]: Options; }, rawArgv: Array = [], -) { +): boolean { const yargsSpecialOptions = ['$0', '_', 'help', 'h']; const deprecationEntries = options.deprecationEntries || {}; const allowedOptions = Object.keys(options).reduce( diff --git a/packages/jest-watcher/src/PatternPrompt.ts b/packages/jest-watcher/src/PatternPrompt.ts index b3c8ceb434e2..abceea3e1dcd 100644 --- a/packages/jest-watcher/src/PatternPrompt.ts +++ b/packages/jest-watcher/src/PatternPrompt.ts @@ -40,7 +40,7 @@ export default class PatternPrompt { onSuccess: (value: string) => void, onCancel: () => void, options?: {header: string}, - ) { + ): void { this._pipe.write(ansiEscapes.cursorHide); this._pipe.write(CLEAR); @@ -57,7 +57,7 @@ export default class PatternPrompt { this._prompt.enter(this._onChange.bind(this), onSuccess, onCancel); } - protected _onChange(_pattern: string, _options: ScrollOptions) { + protected _onChange(_pattern: string, _options: ScrollOptions): void { this._pipe.write(ansiEscapes.eraseLine); this._pipe.write(ansiEscapes.cursorLeft); } diff --git a/packages/jest-watcher/src/lib/Prompt.ts b/packages/jest-watcher/src/lib/Prompt.ts index 88422ed62a01..c8d0897e076e 100644 --- a/packages/jest-watcher/src/lib/Prompt.ts +++ b/packages/jest-watcher/src/lib/Prompt.ts @@ -31,7 +31,7 @@ export default class Prompt { this._onCancel = () => {}; } - private _onResize = () => { + private _onResize = (): void => { this._onChange(); }; @@ -39,7 +39,7 @@ export default class Prompt { onChange: (pattern: string, options: ScrollOptions) => void, onSuccess: (pattern: string) => void, onCancel: () => void, - ) { + ): void { this._entering = true; this._value = ''; this._onSuccess = onSuccess; @@ -58,15 +58,15 @@ export default class Prompt { process.stdout.on('resize', this._onResize); } - setPromptLength(length: number) { + setPromptLength(length: number): void { this._promptLength = length; } - setPromptSelection(selected: string) { + setPromptSelection(selected: string): void { this._selection = selected; } - put(key: string) { + put(key: string): void { switch (key) { case KEYS.ENTER: this._entering = false; @@ -99,13 +99,13 @@ export default class Prompt { } } - abort() { + abort(): void { this._entering = false; this._value = ''; process.stdout.removeListener('resize', this._onResize); } - isEntering() { + isEntering(): boolean { return this._entering; } } diff --git a/packages/jest-watcher/src/lib/colorize.ts b/packages/jest-watcher/src/lib/colorize.ts index cad555eb37ae..056078699bb9 100644 --- a/packages/jest-watcher/src/lib/colorize.ts +++ b/packages/jest-watcher/src/lib/colorize.ts @@ -7,7 +7,7 @@ import chalk = require('chalk'); -export default (str: string, start: number, end: number) => +export default (str: string, start: number, end: number): string => chalk.dim(str.slice(0, start)) + chalk.reset(str.slice(start, end)) + chalk.dim(str.slice(end)); diff --git a/packages/jest-watcher/src/lib/formatTestNameByPattern.ts b/packages/jest-watcher/src/lib/formatTestNameByPattern.ts index 222992c68491..f4aa60f93443 100644 --- a/packages/jest-watcher/src/lib/formatTestNameByPattern.ts +++ b/packages/jest-watcher/src/lib/formatTestNameByPattern.ts @@ -12,7 +12,7 @@ import colorize from './colorize'; const DOTS = '...'; const ENTER = '⏎'; -export default (testName: string, pattern: string, width: number) => { +export default (testName: string, pattern: string, width: number): string => { const inlineTestName = testName.replace(/(\r\n|\n|\r)/gm, ENTER); let regexp; diff --git a/packages/jest-watcher/src/lib/patternModeHelpers.ts b/packages/jest-watcher/src/lib/patternModeHelpers.ts index 5554b5e755bd..6ef76847dbff 100644 --- a/packages/jest-watcher/src/lib/patternModeHelpers.ts +++ b/packages/jest-watcher/src/lib/patternModeHelpers.ts @@ -12,7 +12,7 @@ import stringLength = require('string-length'); export const printPatternCaret = ( pattern: string, pipe: NodeJS.WritableStream, -) => { +): void => { const inputText = `${chalk.dim(' pattern \u203A')} ${pattern}`; pipe.write(ansiEscapes.eraseDown); @@ -24,7 +24,7 @@ export const printRestoredPatternCaret = ( pattern: string, currentUsageRows: number, pipe: NodeJS.WritableStream, -) => { +): void => { const inputText = `${chalk.dim(' pattern \u203A')} ${pattern}`; pipe.write( diff --git a/packages/jest-watcher/src/lib/scroll.ts b/packages/jest-watcher/src/lib/scroll.ts index 977d9e85786b..943a66c8a14a 100644 --- a/packages/jest-watcher/src/lib/scroll.ts +++ b/packages/jest-watcher/src/lib/scroll.ts @@ -7,7 +7,10 @@ import {ScrollOptions} from '../types'; -export default function scroll(size: number, {offset, max}: ScrollOptions) { +export default function scroll( + size: number, + {offset, max}: ScrollOptions, +): {end: number; index: number; start: number} { let start = 0; let index = Math.min(offset, size); diff --git a/packages/jest-worker/src/workers/ChildProcessWorker.ts b/packages/jest-worker/src/workers/ChildProcessWorker.ts index a6b3e3ac02f2..8410fdbf0cf7 100644 --- a/packages/jest-worker/src/workers/ChildProcessWorker.ts +++ b/packages/jest-worker/src/workers/ChildProcessWorker.ts @@ -79,7 +79,7 @@ export default class ChildProcessWorker implements WorkerInterface { this.initialize(); } - initialize() { + initialize(): void { const forceColor = stdoutSupportsColor ? {FORCE_COLOR: '1'} : {}; const child = fork(require.resolve('./processChild'), [], { cwd: process.cwd(), @@ -215,7 +215,11 @@ export default class ChildProcessWorker implements WorkerInterface { } } - send(request: ChildMessage, onProcessStart: OnStart, onProcessEnd: OnEnd) { + send( + request: ChildMessage, + onProcessStart: OnStart, + onProcessEnd: OnEnd, + ): void { onProcessStart(this); this._onProcessEnd = (...args) => { // Clean the request to avoid sending past requests to workers that fail @@ -229,11 +233,11 @@ export default class ChildProcessWorker implements WorkerInterface { this._child.send(request); } - waitForExit() { + waitForExit(): Promise { return this._exitPromise; } - forceExit() { + forceExit(): void { this._child.kill('SIGTERM'); const sigkillTimeout = setTimeout( () => this._child.kill('SIGKILL'), @@ -242,7 +246,7 @@ export default class ChildProcessWorker implements WorkerInterface { this._exitPromise.then(() => clearTimeout(sigkillTimeout)); } - getWorkerId() { + getWorkerId(): number { return this._options.workerId; } diff --git a/packages/jest-worker/src/workers/NodeThreadsWorker.ts b/packages/jest-worker/src/workers/NodeThreadsWorker.ts index 4e300884eef9..64837106eda2 100644 --- a/packages/jest-worker/src/workers/NodeThreadsWorker.ts +++ b/packages/jest-worker/src/workers/NodeThreadsWorker.ts @@ -56,7 +56,7 @@ export default class ExperimentalWorker implements WorkerInterface { this.initialize(); } - initialize() { + initialize(): void { this._worker = new Worker(path.resolve(__dirname, './threadChild.js'), { eval: false, stderr: true, @@ -187,16 +187,20 @@ export default class ExperimentalWorker implements WorkerInterface { } } - waitForExit() { + waitForExit(): Promise { return this._exitPromise; } - forceExit() { + forceExit(): void { this._forceExited = true; this._worker.terminate(); } - send(request: ChildMessage, onProcessStart: OnStart, onProcessEnd: OnEnd) { + send( + request: ChildMessage, + onProcessStart: OnStart, + onProcessEnd: OnEnd, + ): void { onProcessStart(this); this._onProcessEnd = (...args) => { // Clean the request to avoid sending past requests to workers that fail @@ -211,7 +215,7 @@ export default class ExperimentalWorker implements WorkerInterface { this._worker.postMessage(request); } - getWorkerId() { + getWorkerId(): number { return this._options.workerId; } diff --git a/packages/pretty-format/src/collections.ts b/packages/pretty-format/src/collections.ts index 02293f4d1303..62604375608e 100644 --- a/packages/pretty-format/src/collections.ts +++ b/packages/pretty-format/src/collections.ts @@ -28,10 +28,7 @@ const getKeysOfEnumerableProperties = (object: Record) => { * without surrounding punctuation (for example, braces) */ export function printIteratorEntries( - // Flow 0.51.0: property `@@iterator` of $Iterator not found in Object - // To allow simplistic getRecordIterator in immutable.js - // replaced Iterator<[any, any]> with any - iterator: any, + iterator: Iterator, config: Config, indentation: string, depth: number, @@ -130,7 +127,7 @@ export function printIteratorValues( * without surrounding punctuation (for example, brackets) **/ export function printListItems( - list: any, + list: ArrayLike, config: Config, indentation: string, depth: number, diff --git a/packages/pretty-format/src/plugins/AsymmetricMatcher.ts b/packages/pretty-format/src/plugins/AsymmetricMatcher.ts index 197ff0530e5a..aef3fe6eb493 100644 --- a/packages/pretty-format/src/plugins/AsymmetricMatcher.ts +++ b/packages/pretty-format/src/plugins/AsymmetricMatcher.ts @@ -15,14 +15,14 @@ const asymmetricMatcher = : 0x1357a5; const SPACE = ' '; -export const serialize = ( +export const serialize: NewPlugin['serialize'] = ( val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, -): string => { +) => { const stringedValue = val.toString(); if ( @@ -89,7 +89,8 @@ export const serialize = ( return val.toAsymmetricMatcher(); }; -export const test = (val: any) => val && val.$$typeof === asymmetricMatcher; +export const test: NewPlugin['test'] = (val: any) => + val && val.$$typeof === asymmetricMatcher; const plugin: NewPlugin = {serialize, test}; diff --git a/packages/pretty-format/src/plugins/ConvertAnsi.ts b/packages/pretty-format/src/plugins/ConvertAnsi.ts index fac377372f6c..e6d52bbe00b5 100644 --- a/packages/pretty-format/src/plugins/ConvertAnsi.ts +++ b/packages/pretty-format/src/plugins/ConvertAnsi.ts @@ -56,10 +56,10 @@ const toHumanReadableAnsi = (text: string) => } }); -export const test = (val: any): boolean => +export const test: NewPlugin['test'] = (val: any) => typeof val === 'string' && !!val.match(ansiRegex()); -export const serialize = ( +export const serialize: NewPlugin['serialize'] = ( val: string, config: Config, indentation: string, diff --git a/packages/pretty-format/src/plugins/DOMCollection.ts b/packages/pretty-format/src/plugins/DOMCollection.ts index e922cc1bd9f9..f78839e9232a 100644 --- a/packages/pretty-format/src/plugins/DOMCollection.ts +++ b/packages/pretty-format/src/plugins/DOMCollection.ts @@ -17,7 +17,7 @@ const ARRAY_REGEXP = /^(HTML\w*Collection|NodeList)$/; const testName = (name: any) => OBJECT_NAMES.indexOf(name) !== -1 || ARRAY_REGEXP.test(name); -export const test = (val: any) => +export const test: NewPlugin['test'] = (val: any) => val && val.constructor && val.constructor.name && @@ -29,14 +29,14 @@ const propsReducer = (props: any, attribute: any) => { return props; }; -export const serialize = ( +export const serialize: NewPlugin['serialize'] = ( collection: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, -): string => { +) => { const name = collection.constructor.name; if (++depth > config.maxDepth) { return '[' + name + ']'; diff --git a/packages/pretty-format/src/plugins/DOMElement.ts b/packages/pretty-format/src/plugins/DOMElement.ts index 78f2916d5a3a..25bdcfe07b94 100644 --- a/packages/pretty-format/src/plugins/DOMElement.ts +++ b/packages/pretty-format/src/plugins/DOMElement.ts @@ -29,7 +29,7 @@ const testNode = (nodeType: any, name: any) => (nodeType === COMMENT_NODE && name === 'Comment') || (nodeType === FRAGMENT_NODE && name === 'DocumentFragment'); -export const test = (val: any) => +export const test: NewPlugin['test'] = (val: any) => val && val.constructor && val.constructor.name && @@ -49,14 +49,14 @@ function nodeIsFragment(node: HandledType): node is DocumentFragment { return node.nodeType === FRAGMENT_NODE; } -export const serialize = ( +export const serialize: NewPlugin['serialize'] = ( node: HandledType, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, -): string => { +) => { if (nodeIsText(node)) { return printText(node.data, config); } diff --git a/packages/pretty-format/src/plugins/Immutable.ts b/packages/pretty-format/src/plugins/Immutable.ts index 5697feb7a281..ad64a5b3e6ff 100644 --- a/packages/pretty-format/src/plugins/Immutable.ts +++ b/packages/pretty-format/src/plugins/Immutable.ts @@ -50,7 +50,7 @@ const printImmutableEntries = ( // Record has an entries method because it is a collection in immutable v3. // Return an iterator for Immutable Record from version v3 or v4. -const getRecordEntries = (val: any) => { +function getRecordEntries(val: any): Iterator { let i = 0; return { next() { @@ -58,10 +58,10 @@ const getRecordEntries = (val: any) => { const key = val._keys[i++]; return {done: false, value: [key, val.get(key)]}; } - return {done: true}; + return {done: true, value: undefined}; }, }; -}; +} const printImmutableRecord = ( val: any, @@ -169,14 +169,14 @@ const printImmutableValues = ( ) + ']'; -export const serialize = ( +export const serialize: NewPlugin['serialize'] = ( val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, -): string => { +) => { if (val[IS_MAP_SENTINEL]) { return printImmutableEntries( val, @@ -233,7 +233,7 @@ export const serialize = ( // Explicitly comparing sentinel properties to true avoids false positive // when mock identity-obj-proxy returns the key as the value for any key. -export const test = (val: any) => +export const test: NewPlugin['test'] = (val: any) => val && (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); diff --git a/packages/pretty-format/src/plugins/ReactElement.ts b/packages/pretty-format/src/plugins/ReactElement.ts index eda1a992523d..d6d4d03d0995 100644 --- a/packages/pretty-format/src/plugins/ReactElement.ts +++ b/packages/pretty-format/src/plugins/ReactElement.ts @@ -82,14 +82,14 @@ const getPropKeys = (element: any) => { .sort(); }; -export const serialize = ( +export const serialize: NewPlugin['serialize'] = ( element: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, -): string => +) => ++depth > config.maxDepth ? printElementAsLeaf(getType(element), config) : printElement( @@ -115,7 +115,8 @@ export const serialize = ( indentation, ); -export const test = (val: any) => val && ReactIs.isElement(val); +export const test: NewPlugin['test'] = (val: any) => + val && ReactIs.isElement(val); const plugin: NewPlugin = {serialize, test}; diff --git a/packages/pretty-format/src/plugins/ReactTestComponent.ts b/packages/pretty-format/src/plugins/ReactTestComponent.ts index cc9d7b5f0c13..33120bea05e7 100644 --- a/packages/pretty-format/src/plugins/ReactTestComponent.ts +++ b/packages/pretty-format/src/plugins/ReactTestComponent.ts @@ -39,14 +39,14 @@ const getPropKeys = (object: ReactTestObject) => { : []; }; -export const serialize = ( +export const serialize: NewPlugin['serialize'] = ( object: ReactTestObject, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, -): string => +) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement( @@ -76,7 +76,8 @@ export const serialize = ( indentation, ); -export const test = (val: any) => val && val.$$typeof === testSymbol; +export const test: NewPlugin['test'] = val => + val && val.$$typeof === testSymbol; const plugin: NewPlugin = {serialize, test}; diff --git a/packages/pretty-format/src/plugins/lib/markup.ts b/packages/pretty-format/src/plugins/lib/markup.ts index c5ab6a786091..d1ae35e999e1 100644 --- a/packages/pretty-format/src/plugins/lib/markup.ts +++ b/packages/pretty-format/src/plugins/lib/markup.ts @@ -12,7 +12,7 @@ import escapeHTML from './escapeHTML'; // Return empty string if keys is empty. export const printProps = ( keys: Array, - props: any, + props: Record, config: Config, indentation: string, depth: number, @@ -126,7 +126,7 @@ export const printElement = ( ); }; -export const printElementAsLeaf = (type: string, config: Config) => { +export const printElementAsLeaf = (type: string, config: Config): string => { const tagColor = config.colors.tag; return ( tagColor.open + diff --git a/packages/test-utils/src/ConditionalTest.ts b/packages/test-utils/src/ConditionalTest.ts index 961dc7f6c584..6046c5ca8c36 100644 --- a/packages/test-utils/src/ConditionalTest.ts +++ b/packages/test-utils/src/ConditionalTest.ts @@ -9,11 +9,11 @@ import semver = require('semver'); -export function isJestCircusRun() { +export function isJestCircusRun(): boolean { return process.env.JEST_CIRCUS === '1'; } -export function skipSuiteOnJasmine() { +export function skipSuiteOnJasmine(): void { if (!isJestCircusRun()) { test.only('does not work on Jasmine', () => { console.warn('[SKIP] Does not work on Jasmine'); @@ -21,7 +21,7 @@ export function skipSuiteOnJasmine() { } } -export function skipSuiteOnJestCircus() { +export function skipSuiteOnJestCircus(): void { if (isJestCircusRun()) { test.only('does not work on jest-circus', () => { console.warn('[SKIP] Does not work on jest-circus'); @@ -29,7 +29,7 @@ export function skipSuiteOnJestCircus() { } } -export function skipSuiteOnWindows() { +export function skipSuiteOnWindows(): void { if (process.platform === 'win32') { test.only('does not work on Windows', () => { console.warn('[SKIP] Does not work on Windows'); @@ -37,7 +37,10 @@ export function skipSuiteOnWindows() { } } -export function onNodeVersions(versionRange: string, testBody: () => void) { +export function onNodeVersions( + versionRange: string, + testBody: () => void, +): void { if (!semver.satisfies(process.versions.node, versionRange)) { describe.skip(`[SKIP] tests that require node ${versionRange}`, () => { testBody(); diff --git a/packages/test-utils/src/alignedAnsiStyleSerializer.ts b/packages/test-utils/src/alignedAnsiStyleSerializer.ts index a919aafddbf8..a6325ef8341c 100644 --- a/packages/test-utils/src/alignedAnsiStyleSerializer.ts +++ b/packages/test-utils/src/alignedAnsiStyleSerializer.ts @@ -44,7 +44,7 @@ export const alignedAnsiStyleSerializer = { } }); }, - test(val: any): val is string { + test(val: unknown): val is string { return typeof val === 'string'; }, }; diff --git a/yarn.lock b/yarn.lock index 45fc4f2ad557..382010500a55 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2248,7 +2248,7 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-13.7.0.tgz#b417deda18cf8400f278733499ad5547ed1abec4" integrity sha512-GnZbirvmqZUzMgkFn70c74OQpTTUcCzlhQliTzYjQMqg+hVKcDnxdL19Ne3UdYzdMA/+W3eb646FWn/ZaT1NfQ== -"@types/prettier@^1.16.1": +"@types/prettier@^1.19.0": version "1.19.0" resolved "https://registry.yarnpkg.com/@types/prettier/-/prettier-1.19.0.tgz#a2502fb7ce9b6626fdbfc2e2a496f472de1bdd05" integrity sha512-gDE8JJEygpay7IjA/u3JiIURvwZW08f0cZSZLAzFoX/ZmeqvS0Sqv+97aKuHpNsalAMMhwPe+iAS6fQbfmbt7A== @@ -2396,40 +2396,40 @@ dependencies: "@types/yargs-parser" "*" -"@typescript-eslint/eslint-plugin@^2.2.0": - version "2.18.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.18.0.tgz#f8cf272dfb057ecf1ea000fea1e0b3f06a32f9cb" - integrity sha512-kuO8WQjV+RCZvAXVRJfXWiJ8iYEtfHlKgcqqqXg9uUkIolEHuUaMmm8/lcO4xwCOtaw6mY0gStn2Lg4/eUXXYQ== +"@typescript-eslint/eslint-plugin@^2.19.0": + version "2.19.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.19.0.tgz#bf743448a4633e4b52bee0c40148ba072ab3adbd" + integrity sha512-u7IcQ9qwsB6U806LupZmINRnQjC+RJyv36sV/ugaFWMHTbFm/hlLTRx3gGYJgHisxcGSTnf+I/fPDieRMhPSQQ== dependencies: - "@typescript-eslint/experimental-utils" "2.18.0" + "@typescript-eslint/experimental-utils" "2.19.0" eslint-utils "^1.4.3" functional-red-black-tree "^1.0.1" regexpp "^3.0.0" tsutils "^3.17.1" -"@typescript-eslint/experimental-utils@2.18.0", "@typescript-eslint/experimental-utils@^2.5.0": - version "2.18.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-2.18.0.tgz#e4eab839082030282496c1439bbf9fdf2a4f3da8" - integrity sha512-J6MopKPHuJYmQUkANLip7g9I82ZLe1naCbxZZW3O2sIxTiq/9YYoOELEKY7oPg0hJ0V/AQ225h2z0Yp+RRMXhw== +"@typescript-eslint/experimental-utils@2.19.0", "@typescript-eslint/experimental-utils@^2.5.0": + version "2.19.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-2.19.0.tgz#d5ca732f22c009e515ba09fcceb5f2127d841568" + integrity sha512-zwpg6zEOPbhB3+GaQfufzlMUOO6GXCNZq6skk+b2ZkZAIoBhVoanWK255BS1g5x9bMwHpLhX0Rpn5Fc3NdCZdg== dependencies: "@types/json-schema" "^7.0.3" - "@typescript-eslint/typescript-estree" "2.18.0" + "@typescript-eslint/typescript-estree" "2.19.0" eslint-scope "^5.0.0" -"@typescript-eslint/parser@^2.2.0": - version "2.18.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-2.18.0.tgz#d5f7fc1839abd4a985394e40e9d2454bd56aeb1f" - integrity sha512-SJJPxFMEYEWkM6pGfcnjLU+NJIPo+Ko1QrCBL+i0+zV30ggLD90huEmMMhKLHBpESWy9lVEeWlQibweNQzyc+A== +"@typescript-eslint/parser@^2.19.0": + version "2.19.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-2.19.0.tgz#912160d9425395d09857dcd5382352bc98be11ae" + integrity sha512-s0jZoxAWjHnuidbbN7aA+BFVXn4TCcxEVGPV8lWMxZglSs3NRnFFAlL+aIENNmzB2/1jUJuySi6GiM6uACPmpg== dependencies: "@types/eslint-visitor-keys" "^1.0.0" - "@typescript-eslint/experimental-utils" "2.18.0" - "@typescript-eslint/typescript-estree" "2.18.0" + "@typescript-eslint/experimental-utils" "2.19.0" + "@typescript-eslint/typescript-estree" "2.19.0" eslint-visitor-keys "^1.1.0" -"@typescript-eslint/typescript-estree@2.18.0": - version "2.18.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-2.18.0.tgz#cfbd16ed1b111166617d718619c19b62764c8460" - integrity sha512-gVHylf7FDb8VSi2ypFuEL3hOtoC4HkZZ5dOjXvVjoyKdRrvXAOPSzpNRnKMfaUUEiSLP8UF9j9X9EDLxC0lfZg== +"@typescript-eslint/typescript-estree@2.19.0": + version "2.19.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-2.19.0.tgz#6bd7310b9827e04756fe712909f26956aac4b196" + integrity sha512-n6/Xa37k0jQdwpUszffi19AlNbVCR0sdvCs3DmSKMD7wBttKY31lhD2fug5kMD91B2qW4mQldaTEc1PEzvGu8w== dependencies: debug "^4.1.1" eslint-visitor-keys "^1.1.0"