From 8615306aef1a44168a1e0abbff82590f2cc79be0 Mon Sep 17 00:00:00 2001 From: Ahn Date: Thu, 25 Feb 2021 10:39:26 +0100 Subject: [PATCH] build(devs-dep): simplify eslint config (#2403) --- .eslintrc.js | 312 ++++---------------- e2e/__helpers__/test-case/run-descriptor.ts | 2 + e2e/__helpers__/test-case/run-result.ts | 4 +- e2e/__helpers__/test-case/runtime.ts | 9 +- e2e/__helpers__/test-case/types.ts | 1 + e2e/__serializers__/run-result.ts | 2 +- e2e/__tests__/logger.test.ts | 2 +- e2e/__tests__/module-kinds/helpers.ts | 9 +- e2e/__tests__/source-map.test.ts | 1 + package-lock.json | 17 ++ package.json | 1 + src/__helpers__/fakers.ts | 5 +- src/__helpers__/mocks.ts | 8 +- src/__helpers__/path.ts | 1 + src/__helpers__/source-maps.ts | 2 +- src/__serializers__/processed-source.ts | 3 +- src/cli/cli.spec.ts | 3 +- src/cli/config/init.ts | 2 + src/cli/config/migrate.ts | 9 + src/cli/helpers/presets.ts | 1 + src/compiler/ts-compiler.spec.ts | 11 +- src/compiler/ts-compiler.ts | 10 +- src/config/config-set.spec.ts | 64 ++-- src/config/config-set.ts | 15 +- src/raw-compiler-options.ts | 8 +- src/transformers/path-mapping.spec.ts | 4 +- src/ts-jest-transformer.spec.ts | 5 +- src/ts-jest-transformer.ts | 5 +- src/types.ts | 8 +- src/utils/backports.spec.ts | 2 + src/utils/backports.ts | 3 + src/utils/importer.spec.ts | 4 + src/utils/importer.ts | 7 +- src/utils/json.ts | 2 + src/utils/jsonable-value.spec.ts | 1 + src/utils/memoize.spec.ts | 8 + src/utils/memoize.ts | 20 +- src/utils/messages.ts | 1 + src/utils/testing.ts | 5 + src/utils/version-checkers.spec.ts | 1 + 40 files changed, 250 insertions(+), 328 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 8599e2ef3f..787b87dc1b 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -4,266 +4,74 @@ module.exports = { es6: true, 'jest/globals': true, }, - extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/recommended', - 'plugin:@typescript-eslint/recommended-requiring-type-checking', - 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier - 'plugin:jest/recommended', - 'plugin:prettier/recommended' - ], - parser: '@typescript-eslint/parser', parserOptions: { - project: 'tsconfig.json', ecmaVersion: 2020, sourceType: 'module', - impliedStrict: true, ecmaFeatures: { jsx: true, }, }, - plugins: ['@typescript-eslint', 'import', 'jest', 'jsdoc'], - rules: { - 'arrow-body-style': 'warn', - 'arrow-parens': ['off', 'always'], - 'brace-style': ['off', 'off'], - camelcase: 'warn', - 'class-methods-use-this': 'warn', - 'comma-dangle': 'off', - complexity: 'off', - 'constructor-super': 'error', - curly: ['warn', 'multi-line'], - 'default-case': 'error', - 'dot-notation': 'error', - 'eol-last': 'off', - eqeqeq: ['error', 'smart'], - 'for-direction': ['error'], - 'getter-return': 'warn', - 'guard-for-in': 'error', - 'id-match': 'error', - 'import/order': [ - 'error', - { - 'alphabetize': { - 'order': 'asc', - 'caseInsensitive': true, - }, - // this is the default order except for added `internal` in the middle - 'groups': [ - 'builtin', - 'external', - 'internal', - 'parent', - 'sibling', - 'index', - ], - 'newlines-between': 'always', - } - ], - 'jest/valid-title': 'off', - 'jest/no-conditional-expect': 'off', - 'jsdoc/check-alignment': 'error', - 'jsdoc/check-indentation': 'error', - 'jsdoc/newline-after-description': 'warn', - 'linebreak-style': 'off', - 'max-classes-per-file': 'off', - 'max-len': 'off', - 'new-parens': 'off', - 'newline-per-chained-call': 'off', - 'no-bitwise': 'off', - 'no-caller': 'error', - 'no-duplicate-imports': 'error', - 'no-eval': 'error', - 'no-console': 'error', - 'no-async-promise-executor': ['error'], - 'no-case-declarations': ['error'], - 'no-class-assign': ['error'], - 'no-compare-neg-zero': ['error'], - 'no-cond-assign': 'error', - 'no-const-assign': ['error'], - 'no-constant-condition': ['warn'], - 'no-control-regex': ['warn'], - 'no-debugger': 'error', - 'no-delete-var': ['error'], - 'no-dupe-args': ['error'], - 'no-dupe-class-members': 'warn', - 'no-dupe-keys': ['error'], - 'no-duplicate-case': ['error'], - 'no-empty': [ - 'error', - { - allowEmptyCatch: true, - }, - ], - 'no-empty-character-class': ['error'], - 'no-empty-pattern': ['error'], - 'no-ex-assign': ['error'], - 'no-extra-boolean-cast': ['error'], - 'no-extra-semi': 'off', - 'no-fallthrough': 'off', - 'no-func-assign': ['error'], - 'no-global-assign': ['error'], - 'no-inner-declarations': ['error'], - 'no-invalid-this': 'off', - 'no-invalid-regexp': ['error'], - 'no-irregular-whitespace': 'off', - 'no-misleading-character-class': ['error'], - 'no-mixed-spaces-and-tabs': ['error'], - 'no-multiple-empty-lines': 'off', - 'no-new-symbol': ['error'], - 'no-new-wrappers': 'error', - 'no-obj-calls': ['error'], - 'no-octal': ['error'], - 'no-prototype-builtins': ['error'], - 'no-redeclare': 'warn', - 'no-regex-spaces': ['error'], - 'no-return-await': 'error', - 'no-self-assign': ['error'], - 'no-shadow': [ - 'off', - { - hoist: 'all', - }, - ], - 'no-shadow-restricted-names': ['error'], - 'no-sparse-arrays': ['error'], - 'no-template-curly-in-string': 'error', - 'no-this-before-super': ['error'], - 'no-throw-literal': 'error', - 'no-trailing-spaces': 'off', - 'no-undef-init': 'error', - 'no-underscore-dangle': 'off', - 'no-unused-expressions': [ - 'error', - { allowTernary: true }, - ], - 'no-undef': ['error'], - 'no-unexpected-multiline': ['error'], - 'no-unreachable': ['error'], - 'no-unsafe-finally': 'error', - 'no-unsafe-negation': ['error'], - 'no-unused-labels': 'error', - 'no-unused-vars': 'off', // let typescript-eslint handle this - 'no-useless-catch': ['error'], - 'no-useless-escape': 'warn', - 'no-var': 'error', - 'no-with': ['error'], - 'object-shorthand': 'error', - 'one-var': ['error', 'never'], - 'padding-line-between-statements': [ - "error", - { blankLine: "always", prev: "*", next: "return" } - ], - 'prefer-const': 'error', - 'prefer-object-spread': 'error', - 'prefer-template': 'error', - 'prettier/prettier': 'error', - 'quote-props': 'off', - radix: 'error', - 'require-yield': ['error'], - 'space-before-function-paren': 'off', - 'space-in-parens': ['off', 'never'], - 'spaced-comment': [ - 'warn', - 'always', - { - markers: ['/'], - }, - ], - 'use-isnan': 'error', - 'valid-typeof': 'off', - '@typescript-eslint/adjacent-overload-signatures': 'error', - '@typescript-eslint/array-type': [ - 'warn', - { - default: 'array', - }, - ], - '@typescript-eslint/ban-types': [ - 'error', - { - types: { - Object: { - message: 'Avoid using the `Object` type. Did you mean `object`?', - }, - Function: { - message: 'Avoid using the `Function` type. Prefer a specific function type, like `() => void`.', - }, - Boolean: { - message: 'Avoid using the `Boolean` type. Did you mean `boolean`?', - }, - Number: { - message: 'Avoid using the `Number` type. Did you mean `number`?', - }, - String: { - message: 'Avoid using the `String` type. Did you mean `string`?', - }, - Symbol: { - message: 'Avoid using the `Symbol` type. Did you mean `symbol`?', - }, - }, + overrides: [ + { + files: ['*.ts'], + parser: '@typescript-eslint/parser', + parserOptions: { + project: 'tsconfig.json', + impliedStrict: true, + createDefaultProgram: true, }, - ], - '@typescript-eslint/consistent-type-assertions': 'error', - '@typescript-eslint/consistent-type-definitions': 'error', - '@typescript-eslint/explicit-function-return-type': 'off', - '@typescript-eslint/explicit-member-accessibility': [ - 'error', - { - accessibility: 'no-public', - }, - ], - '@typescript-eslint/interface-name-prefix': 'off', - '@typescript-eslint/member-delimiter-style': [ - 'error', - { - multiline: { - delimiter: 'none', - requireLast: true, - }, - singleline: { - delimiter: 'semi', - requireLast: false, - }, - }, - ], - '@typescript-eslint/no-unused-vars': ["error", { "argsIgnorePattern": "^_" }], - '@typescript-eslint/no-empty-function': ['error', { 'allow': ['arrowFunctions']}], - '@typescript-eslint/no-empty-interface': 'off', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/no-for-in-array': 'error', - '@typescript-eslint/no-inferrable-types': 'error', - '@typescript-eslint/no-misused-new': 'error', - '@typescript-eslint/no-namespace': 'warn', - '@typescript-eslint/no-parameter-properties': 'off', - '@typescript-eslint/no-unsafe-assignment': 'off', - '@typescript-eslint/no-unsafe-call': 'off', - '@typescript-eslint/no-unsafe-member-access': 'off', - '@typescript-eslint/no-unsafe-return': 'off', - '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', - '@typescript-eslint/no-unnecessary-type-assertion': 'warn', - '@typescript-eslint/no-use-before-define': 'off', - '@typescript-eslint/no-var-requires': 'off', - '@typescript-eslint/prefer-includes': 'warn', - '@typescript-eslint/prefer-regexp-exec': 'warn', - '@typescript-eslint/prefer-string-starts-ends-with': 'warn', - '@typescript-eslint/prefer-for-of': 'off', - '@typescript-eslint/prefer-function-type': 'error', - '@typescript-eslint/prefer-namespace-keyword': 'error', - '@typescript-eslint/prefer-readonly': 'error', - '@typescript-eslint/prefer-ts-expect-error': 'error', - '@typescript-eslint/require-await': 'off', - '@typescript-eslint/triple-slash-reference': [ - 'error', - { - path: 'always', - types: 'prefer-import', - lib: 'always', + plugins: ['eslint-plugin-prefer-arrow', 'import', 'jsdoc'], + extends: [ + 'plugin:@typescript-eslint/recommended', + 'plugin:jest/recommended', + 'plugin:import/typescript', + 'plugin:prettier/recommended', + ], + rules: { + '@typescript-eslint/array-type': [ + 'error', + { + 'default': 'array-simple', + } + ], + '@typescript-eslint/comma-spacing': 'error', + '@typescript-eslint/no-redeclare': 'error', + '@typescript-eslint/no-unused-vars': ["error", { "argsIgnorePattern": "^_" }], + '@typescript-eslint/no-var-requires': 'off', + '@typescript-eslint/prefer-ts-expect-error': 'error', + 'jest/valid-title': 'off', + 'import/order': [ + 'error', + { + 'alphabetize': { + 'order': 'asc', + 'caseInsensitive': true, + }, + // this is the default order except for added `internal` in the middle + 'groups': [ + 'builtin', + 'external', + 'internal', + 'parent', + 'sibling', + 'index', + ], + 'newlines-between': 'always', + } + ], + 'object-shorthand': 'error', + 'padding-line-between-statements': [ + 'error', + { 'blankLine': 'always', 'prev': '*', 'next': 'return' }, + ], + 'prefer-object-spread': 'error', }, - ], - '@typescript-eslint/type-annotation-spacing': 'off', - '@typescript-eslint/unbound-method': 'off', - '@typescript-eslint/unified-signatures': 'error', + } + ], + rules: { + 'comma-spacing': 'off', + 'no-redeclare': 'off', + 'no-shadow': 'off', + 'quotes': 'off', }, - settings: {}, } diff --git a/e2e/__helpers__/test-case/run-descriptor.ts b/e2e/__helpers__/test-case/run-descriptor.ts index 169bad9833..463e055dbd 100644 --- a/e2e/__helpers__/test-case/run-descriptor.ts +++ b/e2e/__helpers__/test-case/run-descriptor.ts @@ -8,6 +8,7 @@ import type { RunTestOptions, RunWithTemplateIteratorContext, RunWithTemplatesIt export default class RunDescriptor { protected _options: RunTestOptions + // eslint-disable-next-line @typescript-eslint/no-explicit-any protected _sourcePackageJson: any constructor(readonly name: string, options: RunTestOptions = {}) { @@ -18,6 +19,7 @@ export default class RunDescriptor { return join(Paths.e2eSourceDir, this.name) } + // eslint-disable-next-line @typescript-eslint/no-explicit-any get sourcePackageJson(): any { try { return this._sourcePackageJson || (this._sourcePackageJson = require(join(this.sourceDir, 'package.json'))) diff --git a/e2e/__helpers__/test-case/run-result.ts b/e2e/__helpers__/test-case/run-result.ts index 944e9e7862..192c35605e 100644 --- a/e2e/__helpers__/test-case/run-result.ts +++ b/e2e/__helpers__/test-case/run-result.ts @@ -89,7 +89,8 @@ export default class RunResult { if (!this.context.ioDir) { throw new Error('IO not written for test, you must configure the test with `writeIo: true`.') } - let io: any = { in: ['', '', {}, {}], out: '' } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let io: Record = { in: ['', '', {}, {}], out: '' } try { io = require(`${this.context.ioDir}/${relFilePath}.json`) } catch (err) { @@ -127,6 +128,7 @@ export default class RunResult { } return map + // eslint-disable-next-line @typescript-eslint/no-explicit-any .sort((a, b) => ((b.from as any).length || Infinity) - ((a.from as any).length || Infinity)) .reduce((str, { from, to }) => str.replace(typeof from === 'string' ? new RegExp(`${escapeRegex(from)}`, 'g') : from, to), str) } diff --git a/e2e/__helpers__/test-case/runtime.ts b/e2e/__helpers__/test-case/runtime.ts index a49c35a684..0d66127d87 100644 --- a/e2e/__helpers__/test-case/runtime.ts +++ b/e2e/__helpers__/test-case/runtime.ts @@ -47,7 +47,7 @@ eval(process.env.__TS_JEST_EVAL); ` let __hooksSource: string -function hooksSourceWith(vars: Record): string { +function hooksSourceWith(vars: Record): string { if (!__hooksSource) { __hooksSource = readFileSync(join(__dirname, '__hooks-source__.js.hbs'), 'utf8') } @@ -69,6 +69,7 @@ export function run(name: string, options: RunTestOptions = {}): RunResult { // grab base configuration let baseConfig: Config.InitialOptions = require(jestConfigPath()) + // eslint-disable-next-line @typescript-eslint/no-explicit-any if (configFile === 'package.json') baseConfig = (baseConfig as any).jest const extraConfig = {} as Config.InitialOptions @@ -95,6 +96,7 @@ export function run(name: string, options: RunTestOptions = {}): RunResult { merge(extraConfig, jestConfig) } if (options.tsJestConfig) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const globalConfig: any = extraConfig.globals || (extraConfig.globals = {'ts-jest': {}}) const tsJestConfig = globalConfig['ts-jest'] || (globalConfig['ts-jest'] = {}) merge(tsJestConfig, options.tsJestConfig) @@ -152,6 +154,7 @@ export function run(name: string, options: RunTestOptions = {}): RunResult { if (cmdArgs[cmdArgs.length - 1] === '--') cmdArgs.pop() // extend env + // eslint-disable-next-line @typescript-eslint/no-explicit-any const localEnv: any = { ...env } if (inject) { const injected = typeof inject === 'function' ? `(${inject.toString()}).apply(this);` : inject @@ -162,6 +165,7 @@ export function run(name: string, options: RunTestOptions = {}): RunResult { } // arguments to give to spawn + // eslint-disable-next-line @typescript-eslint/no-explicit-any const spawnOptions: { env: Record; cwd: string } = { env: localEnv } as any // create started script for debugging @@ -225,6 +229,7 @@ export function prepareTest(name: string, template: string, options: RunTestOpti const templateDir = join(Paths.e2eWorkTemplatesDir, template) // config utils const configUtils = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any merge: (...objects: any[]) => merge({}, ...objects), } @@ -307,7 +312,7 @@ export function prepareTest(name: string, template: string, options: RunTestOpti // create a package.json if it does not exists, and/or enforce the package name const pkgFile = join(caseWorkdir, 'package.json') - const pkg: any = existsSync(pkgFile) ? readJsonSync(pkgFile) : {} + const pkg: Record = existsSync(pkgFile) ? readJsonSync(pkgFile) : {} pkg.name = name pkg.private = true pkg.version = `0.0.0-mock0` diff --git a/e2e/__helpers__/test-case/types.ts b/e2e/__helpers__/test-case/types.ts index 5421c412c2..272ebfdc7b 100644 --- a/e2e/__helpers__/test-case/types.ts +++ b/e2e/__helpers__/test-case/types.ts @@ -7,6 +7,7 @@ import type RunResult from './run-result' export interface RunTestOptions { template?: string env?: Record + // eslint-disable-next-line @typescript-eslint/no-explicit-any inject?: (() => any) | string writeIo?: boolean jestConfig?: Config.InitialOptions diff --git a/e2e/__serializers__/run-result.ts b/e2e/__serializers__/run-result.ts index 9667bb54e8..3339c80307 100644 --- a/e2e/__serializers__/run-result.ts +++ b/e2e/__serializers__/run-result.ts @@ -1,6 +1,6 @@ import RunResult from '../__helpers__/test-case/run-result' -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +// eslint-disable-next-line export const test = (val: any): boolean => val && val instanceof RunResult export const print = (val: RunResult, _: unknown, indent: (l: string) => unknown): string => [ `${ val.status === 0 ? '√' : '×' } ${ val.cmdLine }`, diff --git a/e2e/__tests__/logger.test.ts b/e2e/__tests__/logger.test.ts index f5cbda5935..3a02c1e790 100644 --- a/e2e/__tests__/logger.test.ts +++ b/e2e/__tests__/logger.test.ts @@ -68,7 +68,7 @@ describe('ts-jest logging', () => { noCache: true, tsJestConfig: { tsconfig: { - target: 'es2020' as any + target: 'es2020' } } }) diff --git a/e2e/__tests__/module-kinds/helpers.ts b/e2e/__tests__/module-kinds/helpers.ts index c5e4d5dc14..c2ebd07fbd 100644 --- a/e2e/__tests__/module-kinds/helpers.ts +++ b/e2e/__tests__/module-kinds/helpers.ts @@ -1,4 +1,5 @@ import tsJestPresets from '../../../presets' +import type { RawCompilerOptions } from "../../../src/raw-compiler-options"; import { PackageSets } from '../../__helpers__/templates' import { configureTestCase } from '../../__helpers__/test-case' import { nodeWithESMSupport } from '../../__helpers__/test-case/utils' @@ -13,11 +14,7 @@ console.log = jest.fn() // System = 4, // ES2015 = 5, // ESNext = 6 -interface TestOptions { - module: string - allowSyntheticDefaultImports?: boolean - esModuleInterop?: boolean -} +type TestOptions = Pick // eslint-disable-next-line jest/no-export export const enum AllPreset { DEFAULT = 'default', @@ -46,7 +43,7 @@ const runTestForOptions = (options: TestOptions, preset: AllPresetType = AllPres const testCase = configureTestCase('module-kinds', { jestConfig: tsJestPresetToUse, - tsJestConfig: { tsconfig: options as any, diagnostics: { warnOnly: true } }, + tsJestConfig: { tsconfig: options, diagnostics: { warnOnly: true } }, noCache: true, }, ) diff --git a/e2e/__tests__/source-map.test.ts b/e2e/__tests__/source-map.test.ts index 1f69849140..8ef6290915 100644 --- a/e2e/__tests__/source-map.test.ts +++ b/e2e/__tests__/source-map.test.ts @@ -4,6 +4,7 @@ import type { TsJestConfig } from '../../src/types' import { allValidPackageSets } from '../__helpers__/templates' import { configureTestCase } from '../__helpers__/test-case' +// eslint-disable-next-line @typescript-eslint/no-explicit-any function runSourceMapTests(tsJestConfig: Partial | any) { const testCase = configureTestCase('source-maps', { writeIo: true, diff --git a/package-lock.json b/package-lock.json index ed43479697..acc3f85b05 100644 --- a/package-lock.json +++ b/package-lock.json @@ -51,6 +51,7 @@ "eslint-plugin-import": "latest", "eslint-plugin-jest": "latest", "eslint-plugin-jsdoc": "latest", + "eslint-plugin-prefer-arrow": "latest", "eslint-plugin-prettier": "latest", "execa": "latest", "fs-extra": "9.x", @@ -4913,6 +4914,15 @@ "spdx-license-ids": "^3.0.0" } }, + "node_modules/eslint-plugin-prefer-arrow": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/eslint-plugin-prefer-arrow/-/eslint-plugin-prefer-arrow-1.2.3.tgz", + "integrity": "sha512-J9I5PKCOJretVuiZRGvPQxCbllxGAV/viI20JO3LYblAodofBxyMnZAJ+WGeClHgANnSJberTNoFWWjrWKBuXQ==", + "dev": true, + "peerDependencies": { + "eslint": ">=2.0.0" + } + }, "node_modules/eslint-plugin-prettier": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.3.1.tgz", @@ -16544,6 +16554,13 @@ } } }, + "eslint-plugin-prefer-arrow": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/eslint-plugin-prefer-arrow/-/eslint-plugin-prefer-arrow-1.2.3.tgz", + "integrity": "sha512-J9I5PKCOJretVuiZRGvPQxCbllxGAV/viI20JO3LYblAodofBxyMnZAJ+WGeClHgANnSJberTNoFWWjrWKBuXQ==", + "dev": true, + "requires": {} + }, "eslint-plugin-prettier": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.3.1.tgz", diff --git a/package.json b/package.json index 6b9f7acf65..8d8d988c4c 100644 --- a/package.json +++ b/package.json @@ -108,6 +108,7 @@ "eslint-plugin-import": "latest", "eslint-plugin-jest": "latest", "eslint-plugin-jsdoc": "latest", + "eslint-plugin-prefer-arrow": "latest", "eslint-plugin-prettier": "latest", "execa": "latest", "fs-extra": "9.x", diff --git a/src/__helpers__/fakers.ts b/src/__helpers__/fakers.ts index 8d48da3202..b23207a319 100644 --- a/src/__helpers__/fakers.ts +++ b/src/__helpers__/fakers.ts @@ -24,7 +24,7 @@ function getJestConfig( const res = { globals: {}, ...options, - } as any + } as any // eslint-disable-line @typescript-eslint/no-explicit-any if (tsJestOptions) { res.globals['ts-jest'] = tsJestOptions } @@ -33,6 +33,7 @@ function getJestConfig( } export function importReason(text = '[[BECAUSE]]'): ImportReasons { + // eslint-disable-next-line @typescript-eslint/no-explicit-any return text as any } @@ -49,6 +50,7 @@ export function createConfigSet({ tsJestConfig?: TsJestGlobalOptions logger?: Logger resolve?: ((path: string) => string) | null + // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any } = {}): ConfigSet { const jestCfg = getJestConfig(jestConfig, tsJestConfig) @@ -86,6 +88,7 @@ export function makeCompiler( ): TsJestCompiler { tsJestConfig = { ...tsJestConfig } tsJestConfig.diagnostics = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any ...(tsJestConfig.diagnostics as any), pretty: false, } diff --git a/src/__helpers__/mocks.ts b/src/__helpers__/mocks.ts index 616aeeca97..51af25064e 100644 --- a/src/__helpers__/mocks.ts +++ b/src/__helpers__/mocks.ts @@ -5,18 +5,22 @@ import { rootLogger } from '../utils/logger' export const logTargetMock = (): testing.LogTargetMock => (rootLogger as testing.LoggerMock).target export const mockObject = (obj: T, newProps: M): T & M & { mockRestore: () => T } => { - const backup: any = Object.create(null) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const backup: Record = Object.create(null) Object.keys(newProps).forEach((key) => { const desc = (backup[key] = Object.getOwnPropertyDescriptor(obj, key)) - const newDesc: any = { ...desc } + const newDesc: Record = { ...desc } if (newDesc.get) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any newDesc.get = () => (newProps as any)[key] } else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any newDesc.value = (newProps as any)[key] } Object.defineProperty(obj, key, newDesc) }) + // eslint-disable-next-line @typescript-eslint/no-explicit-any if ((obj as any).mockRestore) backup.mockRestore = Object.getOwnPropertyDescriptor(obj, 'mockRestore') return Object.defineProperty(obj, 'mockRestore', { diff --git a/src/__helpers__/path.ts b/src/__helpers__/path.ts index ef1ce5b7a8..003a1a88cf 100644 --- a/src/__helpers__/path.ts +++ b/src/__helpers__/path.ts @@ -6,6 +6,7 @@ import { ensureDirSync } from 'fs-extra' export const ROOT = resolve(__dirname, '..', '..') export function tempDir(ns: string): string { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const dir = join(tmpdir(), 'ts-jest-unit-tests', ns, parseInt((Math.random() * 1e17) as any, 10).toString(36)) ensureDirSync(dir) diff --git a/src/__helpers__/source-maps.ts b/src/__helpers__/source-maps.ts index e12baef049..4b7b839a6d 100644 --- a/src/__helpers__/source-maps.ts +++ b/src/__helpers__/source-maps.ts @@ -21,7 +21,7 @@ export interface ParsedSourceWithMaps { } export function parseSource(source: string): ParsedSourceWithMaps { const [comment, b64Maps]: [string, string | undefined] = - // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec + // eslint-disable-next-line (source.match(/[\n^]\/\/#\s*sourceMappingURL=data:application\/json;(?:charset=utf-8;)?base64,(\S+)\s*$/) as any) || [] if (b64Maps) { diff --git a/src/__serializers__/processed-source.ts b/src/__serializers__/processed-source.ts index 46c5627936..e4c1699fb0 100644 --- a/src/__serializers__/processed-source.ts +++ b/src/__serializers__/processed-source.ts @@ -2,8 +2,9 @@ import { dump } from 'js-yaml' import ProcessedSource from '../__helpers__/processed-source' -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +// eslint-disable-next-line export const test = (val: any): boolean => val && val instanceof ProcessedSource +// eslint-disable-next-line @typescript-eslint/no-explicit-any export const print = (val: ProcessedSource, _: unknown, indent: (str: string) => any): string => { const sourceMaps = val.normalizedOutputSourceMaps const out = [ diff --git a/src/cli/cli.spec.ts b/src/cli/cli.spec.ts index 2334badcc5..fcc6cd772d 100644 --- a/src/cli/cli.spec.ts +++ b/src/cli/cli.spec.ts @@ -13,7 +13,7 @@ const fs = mocked(_fs) let lastExitCode: number | undefined const runCli = async ( - ...args: any[] + ...args: any[] // eslint-disable-line @typescript-eslint/no-explicit-any ): Promise<{ stdout: string; stderr: string; exitCode: number | undefined; log: string }> => { mockedProcess.stderr.clear() mockedProcess.stdout.clear() @@ -30,6 +30,7 @@ const runCli = async ( } } +// eslint-disable-next-line @typescript-eslint/no-explicit-any let mockedProcess: any const FAKE_CWD = normalize('/foo/bar') const FAKE_PKG = normalize(`${FAKE_CWD}/package.json`) diff --git a/src/cli/config/init.ts b/src/cli/config/init.ts index f1f9f76058..6a31687d80 100644 --- a/src/cli/config/init.ts +++ b/src/cli/config/init.ts @@ -73,9 +73,11 @@ export const run: CliCommand = async (args: Arguments /* , logger: Logger */) => if (isPackage) { // package.json config + // eslint-disable-next-line @typescript-eslint/no-explicit-any const base: any = jestPreset ? { preset: preset.name } : { ...preset.value } if (!jsdom) base.testEnvironment = 'node' if (tsconfig || shouldPostProcessWithBabel) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const tsJestConf: any = {} base.globals = { 'ts-jest': tsJestConf } if (tsconfig) tsJestConf.tsconfig = tsconfig diff --git a/src/cli/config/migrate.ts b/src/cli/config/migrate.ts index 954d30ad48..aa01504df2 100644 --- a/src/cli/config/migrate.ts +++ b/src/cli/config/migrate.ts @@ -29,6 +29,7 @@ export const run: CliCommand = async (args: Arguments /* , logger: Logger*/) => } let actualConfig: Config.InitialOptions = require(filePath) if (isPackage) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any actualConfig = (actualConfig as any).jest } if (!actualConfig) actualConfig = {} @@ -47,6 +48,7 @@ export const run: CliCommand = async (args: Arguments /* , logger: Logger*/) => // try to detect what transformer the js extensions would target const jsTransformers = Object.keys(migratedConfig.transform || {}).reduce((list, pattern) => { if (RegExp(pattern.replace(/^\/?/, '/dummy-project/')).test('/dummy-project/src/foo.js')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any let transformer: string = (migratedConfig.transform as any)[pattern] if (/\bbabel-jest\b/.test(transformer)) transformer = 'babel-jest' else if (/\ts-jest\b/.test(transformer)) transformer = 'ts-jest' @@ -80,6 +82,7 @@ Visit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more inf if (args.jestPreset === false) { delete migratedConfig.preset } else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any preset = (allPresets as any)[migratedConfig.preset] || defaults } } @@ -97,6 +100,7 @@ Visit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more inf } // there is a testRegex, remove our testMatch if (migratedConfig.testRegex && preset) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any migratedConfig.testMatch = null as any } // check the testMatch @@ -111,8 +115,10 @@ Visit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more inf // migrate the transform if (migratedConfig.transform) { Object.keys(migratedConfig.transform).forEach((key) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const val = (migratedConfig.transform as any)[key] if (typeof val === 'string' && /\/?ts-jest(?:\/preprocessor\.js)?$/.test(val)) { + // eslint-disable-next-line ;(migratedConfig.transform as any)[key] = 'ts-jest' } }) @@ -179,7 +185,9 @@ ${footNotes.join('\n')} function cleanupConfig(config: Config.InitialOptions): void { if (config.globals) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any if ((config as any).globals['ts-jest'] && Object.keys((config as any).globals['ts-jest']).length === 0) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any delete (config as any).globals['ts-jest'] } if (Object.keys(config.globals).length === 0) { @@ -200,6 +208,7 @@ function cleanupConfig(config: Config.InitialOptions): void { if (config.preset === JestPresetNames.default) config.preset = defaults.name } +// eslint-disable-next-line @typescript-eslint/no-explicit-any function dedupSort(arr: any[]) { return arr .filter((s, i, a) => a.findIndex((e) => s.toString() === e.toString()) === i) diff --git a/src/cli/helpers/presets.ts b/src/cli/helpers/presets.ts index 3055b37790..5c9d82a0b7 100644 --- a/src/cli/helpers/presets.ts +++ b/src/cli/helpers/presets.ts @@ -49,6 +49,7 @@ const definePreset = (fullName: string): TsJestPresetDescriptor => ({ }) /** @internal */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export const allPresets: Record = {} as any /** @internal */ export const defaults = (allPresets[JestPresetNames.default] = definePreset(JestPresetNames.default)) diff --git a/src/compiler/ts-compiler.spec.ts b/src/compiler/ts-compiler.spec.ts index 40ff99c7df..4643de8fdb 100644 --- a/src/compiler/ts-compiler.spec.ts +++ b/src/compiler/ts-compiler.spec.ts @@ -54,7 +54,7 @@ describe('TsCompiler', () => { tsJestConfig: { ...baseTsJestConfig, tsconfig: { - jsx: 'preserve' as any, + jsx: 'preserve', }, }, }) @@ -68,7 +68,7 @@ describe('TsCompiler', () => { tsJestConfig: { ...baseTsJestConfig, tsconfig: { - jsx: 'react' as any, + jsx: 'react', }, }, }) @@ -287,7 +287,7 @@ const t: string = f(5) { tsJestConfig: { tsconfig: { - jsx: 'preserve' as any, + jsx: 'preserve', }, }, }, @@ -304,7 +304,7 @@ const t: string = f(5) { tsJestConfig: { tsconfig: { - jsx: 'react' as any, + jsx: 'react', }, }, }, @@ -360,6 +360,7 @@ const t: string = f(5) it(`should use moduleResolutionCache`, () => { jest.unmock('typescript') const ts = require('typescript') + // eslint-disable-next-line @typescript-eslint/no-empty-function const moduleResolutionCacheMock = (ts.createModuleResolutionCache = jest.fn().mockImplementation(() => {})) makeCompiler({ @@ -499,7 +500,7 @@ const t: string = f(5) // eslint-disable-next-line no-console expect(console.log).toHaveBeenCalled() - // eslint-disable-next-line no-console + // eslint-disable-next-line expect(((console.log as any) as jest.MockInstance).mock.calls[0][0].emit).toBeDefined() }) }) diff --git a/src/compiler/ts-compiler.ts b/src/compiler/ts-compiler.ts index 282f4b79ad..e62af47a95 100644 --- a/src/compiler/ts-compiler.ts +++ b/src/compiler/ts-compiler.ts @@ -110,6 +110,7 @@ export class TsCompiler implements TsCompilerInstance { // If we don't return `undefined` it results in `undefined === "undefined"` and run // `createProgram` again (which is very slow). Using a `string` assertion here to avoid // TypeScript errors from the function signature (expects `(x: string) => string`). + // eslint-disable-next-line @typescript-eslint/no-explicit-any return version === undefined ? ((undefined as any) as string) : String(version) }, getScriptSnapshot: (fileName: string) => { @@ -144,7 +145,7 @@ export class TsCompiler implements TsCompilerInstance { getCompilationSettings: () => this._compilerOptions, getDefaultLibFileName: () => this._ts.getDefaultLibFilePath(this._compilerOptions), getCustomTransformers: () => this._makeTransformers(this.configSet.resolvedTransformers), - resolveModuleNames: (moduleNames: string[], containingFile: string): (ResolvedModuleFull | undefined)[] => + resolveModuleNames: (moduleNames: string[], containingFile: string): Array => moduleNames.map((moduleName) => { const { resolvedModule } = this._ts.resolveModuleName( moduleName, @@ -168,6 +169,7 @@ export class TsCompiler implements TsCompilerInstance { this._updateMemoryCache(fileContent, fileName) // See https://github.com/microsoft/TypeScript/blob/master/src/compiler/utilities.ts#L164 + // eslint-disable-next-line @typescript-eslint/no-explicit-any return (this._languageService?.getProgram()?.getSourceFile(fileName) as any)?.resolvedModules } @@ -244,13 +246,13 @@ export class TsCompiler implements TsCompilerInstance { return { before: customTransformers.before.map((beforeTransformer) => beforeTransformer.factory(this, beforeTransformer.options), - ) as (TransformerFactory | CustomTransformerFactory)[], + ) as Array | CustomTransformerFactory>, after: customTransformers.after.map((afterTransformer) => afterTransformer.factory(this, afterTransformer.options), - ) as (TransformerFactory | CustomTransformerFactory)[], + ) as Array | CustomTransformerFactory>, afterDeclarations: customTransformers.afterDeclarations.map((afterDeclarations) => afterDeclarations.factory(this, afterDeclarations.options), - ) as TransformerFactory[], + ) as Array>, } } diff --git a/src/config/config-set.spec.ts b/src/config/config-set.spec.ts index fdea8bc389..1e730bcbdd 100644 --- a/src/config/config-set.spec.ts +++ b/src/config/config-set.spec.ts @@ -40,7 +40,7 @@ describe('parsedTsConfig', () => { }) it('should include compiler config from base config', () => { - expect(get({ tsconfig: { target: 'esnext' } as any }).options.target).toBe(ts.ScriptTarget.ESNext) + expect(get({ tsconfig: { target: 'esnext' } }).options.target).toBe(ts.ScriptTarget.ESNext) }) it('should fallback to ES2015 as default target and CommonJS as default module when no target or module defined in tsconfig', () => { @@ -73,7 +73,7 @@ describe('parsedTsConfig', () => { target.clear() const cs = createConfigSet({ tsJestConfig: { - tsconfig: { module: 'AMD', esModuleInterop: false } as any, + tsconfig: { module: 'AMD', esModuleInterop: false }, diagnostics: { warnOnly: true, pretty: false }, }, resolve: null, @@ -95,7 +95,7 @@ describe('parsedTsConfig', () => { target.clear() const cs = createConfigSet({ tsJestConfig: { - tsconfig: { module: 'amd', esModuleInterop: false } as any, + tsconfig: { module: 'amd', esModuleInterop: false }, diagnostics: { warnOnly: true, pretty: false }, babelConfig: { babelrc: false }, }, @@ -157,7 +157,7 @@ describe('customTransformers', () => { jestConfig: { rootDir: 'src', cwd: 'src', - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any tsJestConfig: { astTransformers: data, }, @@ -361,7 +361,7 @@ describe('tsCacheDir', () => { devDependencies: { dev: '1.2.5' }, dependencies: { std: '1.2.6' }, } - const realVersions: any = { + const realVersions: Record = { peer: '0.1.0', dev: '4.3.2', std: '9.10.2', @@ -400,25 +400,25 @@ describe('isTestFile', () => { jestConfig: { testRegex: [{}], testMatch: [], - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }, { jestConfig: { testMatch: [], testRegex: [/.*\.(spec|test)\.[jt]sx?$/], - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }, { jestConfig: { testMatch: ['**/?(*.)+(spec|test).[tj]s?(x)'], testRegex: [], - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }, { jestConfig: { testMatch: ['**/?(*.)+(spec|test).[tj]s?(x)'], testRegex: ['**/?(*.)+(foo|bar).[tj]s?(x)'], - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }, ])('should return a boolean value whether the file matches test pattern', (config) => { expect(createConfigSet(config).isTestFile('foo.spec.ts')).toMatchSnapshot() @@ -427,11 +427,13 @@ describe('isTestFile', () => { describe('shouldStringifyContent', () => { it('should return correct value is defined', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const cs1 = createConfigSet({ tsJestConfig: { tsconfig: false, stringifyContentPathRegex: '\\.str$' } as any }) expect(cs1.shouldStringifyContent('/foo/bar.ts')).toBe(false) expect(cs1.shouldStringifyContent('/foo/bar.str')).toBe(true) + // eslint-disable-next-line @typescript-eslint/no-explicit-any const cs2 = createConfigSet({ tsJestConfig: { tsconfig: false, stringifyContentPathRegex: /\.str$/ } as any }) expect(cs2.shouldStringifyContent('/foo/bar.ts')).toBe(false) @@ -439,7 +441,7 @@ describe('shouldStringifyContent', () => { }) it('should return correct value when stringifyContentPathRegex is undefined', () => { - const cs = createConfigSet({ tsJestConfig: { tsconfig: false } as any }) + const cs = createConfigSet({ tsJestConfig: { tsconfig: false } }) expect(cs.shouldStringifyContent('/foo/bar.ts')).toBe(false) }) @@ -454,7 +456,8 @@ describe('raiseDiagnostics', () => { messageText = 'foo', code = 9999, category = ts.DiagnosticCategory.Warning, - }: Partial = {}): ts.Diagnostic => ({ messageText, code, category } as any) + }: // eslint-disable-next-line @typescript-eslint/no-explicit-any + Partial = {}): ts.Diagnostic => ({ messageText, code, category } as any) it('should throw when warnOnly is false', () => { const cs = createConfigSet({ filterDiagnostics, logger, tsJestConfig: { diagnostics: { pretty: false } } }) @@ -488,7 +491,8 @@ describe('raiseDiagnostics', () => { messageText = 'foo', code = 9999, category = ts.DiagnosticCategory.Warning, - }: Partial = {}): ts.Diagnostic => ({ messageText, code, category } as any) + }: // eslint-disable-next-line @typescript-eslint/no-explicit-any + Partial = {}): ts.Diagnostic => ({ messageText, code, category } as any) it('should throw when diagnostics contains file path and exclude config matches file path', () => { const cs = createConfigSet({ logger, @@ -524,7 +528,8 @@ describe('raiseDiagnostics', () => { code = 9999, category = ts.DiagnosticCategory.Warning, file = program.getSourceFiles().find((sourceFile) => sourceFile.fileName === 'src/__mocks__/index.ts'), - }: Partial = {}): ts.Diagnostic => ({ messageText, code, category, file } as any) + }: // eslint-disable-next-line @typescript-eslint/no-explicit-any + Partial = {}): ts.Diagnostic => ({ messageText, code, category, file } as any) it("should not throw when exclude config doesn't match source file path", () => { const cs = createConfigSet({ @@ -556,12 +561,13 @@ describe('shouldReportDiagnostics', () => { tsJestConfig: { tsconfig: false, diagnostics: { exclude: ['**/foo/*.ts', '**/foo/*.tsx'] }, - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) expect(cs.shouldReportDiagnostics('/foo/index.ts')).toBe(true) expect(cs.shouldReportDiagnostics('/bar/index.tsx')).toBe(false) + // eslint-disable-next-line @typescript-eslint/no-explicit-any cs = createConfigSet({ tsJestConfig: { tsconfig: false } as any }) expect(cs.shouldReportDiagnostics('/foo/index.ts')).toBe(true) @@ -593,6 +599,7 @@ describe('shouldReportDiagnostics', () => { describe('resolvePath', () => { it('should resolve paths', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const cs = createConfigSet({ jestConfig: { rootDir: '/root', cwd: '/cwd' } as any, resolve: null }) const doResolve = (path: string) => cs.resolvePath(path, { throwIfMissing: false }) expect(doResolve('bar.js')).toBe(resolve('/cwd/bar.js')) @@ -601,6 +608,7 @@ describe('resolvePath', () => { expect(doResolve('/bar.js')).toBe(resolve('/root//bar.js')) }) it('should resolve node paths', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const cs = createConfigSet({ jestConfig: { rootDir: '/root', cwd: '/cwd' } as any, resolve: null }) const doResolve = (path: string) => cs.resolvePath(path, { throwIfMissing: false, nodeResolve: true }) expect(doResolve('json5')).toBe(resolve(__dirname, '../../node_modules/json5', require('json5/package.json').main)) @@ -609,6 +617,7 @@ describe('resolvePath', () => { expect(doResolve('/bar.js')).toBe(resolve('/root//bar.js')) }) it('should throw for invalid paths', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const cs = createConfigSet({ jestConfig: { rootDir: __dirname, cwd: __dirname } as any, resolve: null }) const doResolve = (path: string) => cs.resolvePath(path) expect(() => doResolve('bar.js')).toThrow() @@ -620,6 +629,7 @@ describe('resolvePath', () => { describe('_resolveTsConfig', () => { let findConfig!: jest.SpyInstance + // eslint-disable-next-line @typescript-eslint/no-explicit-any let readConfig!: jest.SpyInstance<{ config?: any; error?: ts.Diagnostic }> let parseConfig!: jest.SpyInstance let cs!: ConfigSet @@ -642,7 +652,7 @@ describe('_resolveTsConfig', () => { readConfig.mockReturnValue({ error: { code: 404, - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) }) @@ -653,6 +663,7 @@ describe('_resolveTsConfig', () => { }) it('should use correct paths when searching', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any cs = createConfigSet({ jestConfig: { rootDir: '/root', cwd: '/cwd' } as any }) const conf = cs.parsedTsConfig @@ -664,6 +675,7 @@ describe('_resolveTsConfig', () => { it('should use given tsconfig path', () => { jest.spyOn(ConfigSet.prototype, 'resolvePath').mockReturnValueOnce('/foo/tsconfig.bar.json') + // eslint-disable-next-line @typescript-eslint/no-empty-function jest.spyOn(ConfigSet.prototype, 'raiseDiagnostics').mockImplementationOnce(() => {}) cs = createConfigSet({ @@ -671,7 +683,7 @@ describe('_resolveTsConfig', () => { rootDir: '/root', cwd: '/cwd', globals: { 'ts-jest': { tsconfig: 'tsconfig.bar.json' } }, - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const conf = cs.parsedTsConfig @@ -695,6 +707,7 @@ describe('_resolveTsConfig', () => { describe('module in tsConfig is not the same as forced module and esModuleInterop is not in tsConfig', () => { beforeEach(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any parseConfig.mockImplementation((conf: any) => ({ options: { ...conf, @@ -716,7 +729,7 @@ describe('_resolveTsConfig', () => { jestConfig: { rootDir: '/root', cwd: '/cwd', - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const conf = cs.parsedTsConfig @@ -739,7 +752,7 @@ describe('_resolveTsConfig', () => { cwd: '/cwd', globals: { 'ts-jest': { tsconfig: 'tsconfig.bar.json' } }, extensionsToTreatAsEsm: ['.ts'], - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const conf = cs.parsedTsConfig @@ -754,6 +767,7 @@ describe('_resolveTsConfig', () => { describe('module in tsConfig is not the same as forced module and allowSyntheticDefaultImports is false in tsConfig', () => { beforeEach(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any parseConfig.mockImplementation((conf: any) => ({ options: { ...conf, @@ -778,7 +792,7 @@ describe('_resolveTsConfig', () => { rootDir: '/root', cwd: '/cwd', globals: { 'ts-jest': { tsconfig: 'tsconfig.json' } }, - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const conf = cs.parsedTsConfig @@ -800,7 +814,7 @@ describe('_resolveTsConfig', () => { cwd: '/cwd', globals: { 'ts-jest': { tsconfig: 'tsconfig.bar.json' } }, extensionsToTreatAsEsm: ['.ts'], - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const conf = cs.parsedTsConfig @@ -815,6 +829,7 @@ describe('_resolveTsConfig', () => { describe('module in tsConfig is the same as forced module and esModuleInterop true is in tsConfig', () => { beforeEach(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any parseConfig.mockImplementation((conf: any) => ({ options: { ...conf, @@ -839,7 +854,7 @@ describe('_resolveTsConfig', () => { rootDir: '/root', cwd: '/cwd', globals: { 'ts-jest': { tsconfig: 'tsconfig.json' } }, - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const conf = cs.parsedTsConfig @@ -862,7 +877,7 @@ describe('_resolveTsConfig', () => { cwd: '/cwd', globals: { 'ts-jest': { tsconfig: 'tsconfig.bar.json' } }, extensionsToTreatAsEsm: ['.ts'], - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const conf = cs.parsedTsConfig @@ -877,6 +892,7 @@ describe('_resolveTsConfig', () => { describe('module in tsConfig is the same as forced module and allowSyntheticDefaultImports true is in tsConfig', () => { beforeEach(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any parseConfig.mockImplementation((conf: any) => ({ options: { ...conf, @@ -901,7 +917,7 @@ describe('_resolveTsConfig', () => { rootDir: '/root', cwd: '/cwd', globals: { 'ts-jest': { tsconfig: 'tsconfig.json' } }, - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const conf = cs.parsedTsConfig @@ -924,7 +940,7 @@ describe('_resolveTsConfig', () => { cwd: '/cwd', globals: { 'ts-jest': { tsconfig: 'tsconfig.bar.json' } }, extensionsToTreatAsEsm: ['.ts'], - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const conf = cs.parsedTsConfig diff --git a/src/config/config-set.ts b/src/config/config-set.ts index 36a3f36d4d..4db6cbff57 100644 --- a/src/config/config-set.ts +++ b/src/config/config-set.ts @@ -69,11 +69,10 @@ const enum DiagnosticCodes { const normalizeRegex = (pattern: string | RegExp | undefined): string | undefined => pattern ? (typeof pattern === 'string' ? pattern : pattern.source) : undefined -const toDiagnosticCode = (code: any): number | undefined => - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions +const toDiagnosticCode = (code?: string | number): number | undefined => code ? parseInt(`${code}`.trim().replace(/^TS/, ''), 10) ?? undefined : undefined -const toDiagnosticCodeList = (items: (string | number)[], into: number[] = []): number[] => { +const toDiagnosticCodeList = (items: Array, into: number[] = []): number[] => { for (let item of items) { if (typeof item === 'string') { const children = item.trim().split(/\s*,\s*/g) @@ -103,6 +102,7 @@ export class ConfigSet { readonly rootDir: string cacheSuffix!: string tsCacheDir: string | undefined + // eslint-disable-next-line @typescript-eslint/no-explicit-any parsedTsConfig!: ParsedCommandLine | Record resolvedTransformers: TsJestAstTransformer = { before: [], @@ -133,7 +133,7 @@ export class ConfigSet { /** * @internal */ - private readonly _matchablePatterns: (string | RegExp)[] + private readonly _matchablePatterns: Array /** * @internal */ @@ -196,7 +196,7 @@ export class ConfigSet { this._matchablePatterns.push(...DEFAULT_JEST_TEST_MATCH) } this._matchTestFilePath = globsToMatcher( - this._matchablePatterns.filter((pattern: any) => typeof pattern === 'string') as string[], + this._matchablePatterns.filter((pattern: string | RegExp) => typeof pattern === 'string') as string[], ) } @@ -256,7 +256,7 @@ export class ConfigSet { // diagnostics const diagnosticsOpt = options.diagnostics ?? true - const ignoreList: (string | number)[] = [...IGNORE_DIAGNOSTIC_CODES] + const ignoreList: Array = [...IGNORE_DIAGNOSTIC_CODES] if (typeof diagnosticsOpt === 'object') { const { ignoreCodes } = diagnosticsOpt if (ignoreCodes) { @@ -298,7 +298,7 @@ export class ConfigSet { this.resolvedTransformers.before = [require('../transformers/hoist-jest')] const { astTransformers } = options if (astTransformers) { - const resolveTransformers = (transformers: (string | AstTransformer)[]): AstTransformerDesc[] => + const resolveTransformers = (transformers: Array): AstTransformerDesc[] => transformers.map((transformer) => { if (typeof transformer === 'string') { return require(this.resolvePath(transformer, { nodeResolve: true })) @@ -473,6 +473,7 @@ export class ConfigSet { * Load TypeScript configuration. Returns the parsed TypeScript config and any `tsconfig` options specified in ts-jest * Subclasses which extend `ConfigSet` can override the default behavior */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any protected _resolveTsConfig(compilerOptions?: RawCompilerOptions, resolvedConfigFile?: string): Record // eslint-disable-next-line no-dupe-class-members protected _resolveTsConfig(compilerOptions?: RawCompilerOptions, resolvedConfigFile?: string): ParsedCommandLine { diff --git a/src/raw-compiler-options.ts b/src/raw-compiler-options.ts index 44dfcea6db..b4c818bd65 100644 --- a/src/raw-compiler-options.ts +++ b/src/raw-compiler-options.ts @@ -69,10 +69,10 @@ export interface RawCompilerOptions { paths?: { [k: string]: string[] } - plugins?: { + plugins?: Array<{ name?: string [k: string]: unknown - }[] + }> rootDirs?: string[] typeRoots?: string[] types?: string[] @@ -83,7 +83,7 @@ export interface RawCompilerOptions { noImplicitUseStrict?: boolean listEmittedFiles?: boolean disableSizeLimit?: boolean - lib?: ( + lib?: Array< | 'ES5' | 'ES6' | 'ES2015' @@ -133,7 +133,7 @@ export interface RawCompilerOptions { | 'ScriptHost' | 'WebWorker' | 'WebWorker.ImportScripts' - )[] + > strictNullChecks?: boolean maxNodeModuleJsDepth?: number importHelpers?: boolean diff --git a/src/transformers/path-mapping.spec.ts b/src/transformers/path-mapping.spec.ts index 7ab86020c7..654dbf82e3 100644 --- a/src/transformers/path-mapping.spec.ts +++ b/src/transformers/path-mapping.spec.ts @@ -59,7 +59,7 @@ describe('path-mapping', () => { resolvedModule: { resolvedFileName: require.resolve('../utils/json'), extension: 'ts', - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const out = transpile(TS_JS_CODE_WITH_PATH_ALIAS) @@ -115,7 +115,7 @@ describe('path-mapping', () => { resolvedModule: { resolvedFileName: resolvedFileNameStub, extension, - } as any, + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any }) const out = transpile(code) diff --git a/src/ts-jest-transformer.spec.ts b/src/ts-jest-transformer.spec.ts index 001d40934e..43e9ca08af 100644 --- a/src/ts-jest-transformer.spec.ts +++ b/src/ts-jest-transformer.spec.ts @@ -150,12 +150,13 @@ Array [ fileName: 'foo.ts', transformOptions: { configString: '{"foo": "bar"}', + // eslint-disable-next-line @typescript-eslint/no-explicit-any config: { foo: 'bar', testMatch: [], testRegex: [], extensionsToTreatAsEsm: [] } as any, instrument: false, rootDir: '/foo', cacheFS: new Map(), }, - } as any + } as any // eslint-disable-line @typescript-eslint/no-explicit-any const transformOptionsWithCache = { ...input.transformOptions, config: { @@ -276,7 +277,7 @@ Array [ extensionsToTreatAsEsm: [], }, cacheFS: new Map(), - } as any + } as any // eslint-disable-line @typescript-eslint/no-explicit-any let tr!: TsJestTransformer beforeEach(() => { diff --git a/src/ts-jest-transformer.ts b/src/ts-jest-transformer.ts index 8a7aeeb263..223a8355b7 100644 --- a/src/ts-jest-transformer.ts +++ b/src/ts-jest-transformer.ts @@ -28,6 +28,7 @@ interface CachedConfigSet { } interface TsJestHooksMap { + // eslint-disable-next-line @typescript-eslint/no-explicit-any afterProcess?(args: any[], result: string | TransformedSource): string | TransformedSource | void } @@ -97,8 +98,8 @@ export class TsJestTransformer implements Transformer { const jest = { ...config } // we need to remove some stuff from jest config // this which does not depend on config - jest.name = undefined as any - jest.cacheDirectory = undefined as any + jest.name = undefined as any // eslint-disable-line @typescript-eslint/no-explicit-any + jest.cacheDirectory = undefined as any // eslint-disable-line @typescript-eslint/no-explicit-any this._transformCfgStr = `${new JsonableValue(jest).serialized}${configSet.cacheSuffix}` this._createCompiler(configSet, cacheFS) this._getFsCachedResolvedModules(configSet) diff --git a/src/types.ts b/src/types.ts index 8f708dd632..c688d20fda 100644 --- a/src/types.ts +++ b/src/types.ts @@ -46,9 +46,9 @@ export interface AstTransformer> { } export interface ConfigCustomTransformer { - before?: (string | AstTransformer)[] - after?: (string | AstTransformer)[] - afterDeclarations?: (string | AstTransformer)[] + before?: Array + after?: Array + afterDeclarations?: Array } export interface TsJestGlobalOptions { @@ -106,7 +106,7 @@ export interface TsJestGlobalOptions { * @see https://github.com/Microsoft/TypeScript/blob/master/src/compiler/diagnosticMessages.json * @default [6059,18002,18003] */ - ignoreCodes?: number | string | (number | string)[] + ignoreCodes?: number | string | Array /** * If specified, diagnostics of source files which path **matches** will be ignored */ diff --git a/src/utils/backports.spec.ts b/src/utils/backports.spec.ts index 24851d3530..675ba482e0 100644 --- a/src/utils/backports.spec.ts +++ b/src/utils/backports.spec.ts @@ -13,8 +13,10 @@ beforeEach(() => { }) describe('backportJestConfig', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const makeTestsFor = (oldPath: string, _: string, values: any[]) => { values.forEach((val) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any let original: any beforeEach(() => { original = {} diff --git a/src/utils/backports.ts b/src/utils/backports.ts index 2bf5bae900..2b0085fa40 100644 --- a/src/utils/backports.ts +++ b/src/utils/backports.ts @@ -14,8 +14,10 @@ export const backportJestConfig = { logger.debug({ ...context, config }, 'backporting config') + // eslint-disable-next-line @typescript-eslint/no-explicit-any const { globals = {} } = (config || {}) as any const { 'ts-jest': tsJest = {} } = globals + // eslint-disable-next-line @typescript-eslint/no-explicit-any const mergeTsJest: any = {} let hadWarnings = false const warnConfig = (oldPath: string, newPath: string, note?: string) => { @@ -93,6 +95,7 @@ export const backportJestConfig = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const err: any = new Error(`Module not found: ${mod}.`) err.code = 'MODULE_NOT_FOUND' throw err @@ -10,8 +11,10 @@ const moduleNotFound = (mod: string) => { const fakeFullPath = (mod: string) => `/root/${mod}.js` const requireModule = jest.fn((mod) => (mod in modules ? modules[mod]() : moduleNotFound(mod))) const resolveModule = jest.fn((mod) => (mod in modules ? fakeFullPath(mod) : moduleNotFound(mod))) +// eslint-disable-next-line @typescript-eslint/no-explicit-any __requireModule(requireModule as any, resolveModule) +// eslint-disable-next-line @typescript-eslint/no-explicit-any let modules!: { [key: string]: () => any } beforeEach(() => { modules = {} @@ -57,6 +60,7 @@ Object { path: fakeFullPath('fail1'), }) expect(res).not.toHaveProperty('exports') + // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((res as any).error.message).toMatch(/\bfoo\b/) }) }) diff --git a/src/utils/importer.ts b/src/utils/importer.ts index 9f5c5ec969..4ec31318bf 100644 --- a/src/utils/importer.ts +++ b/src/utils/importer.ts @@ -5,6 +5,7 @@ import { Memoize } from './memoize' import { Errors, Helps, ImportReasons, interpolate } from './messages' import { VersionCheckers } from './version-checkers' +// eslint-disable-next-line @typescript-eslint/no-explicit-any type ModulePatcher = (module: T) => T const logger = rootLogger.child({ namespace: 'Importer' }) @@ -15,9 +16,10 @@ const logger = rootLogger.child({ namespace: 'Importer' }) // case it can't import. interface ImportOptions { alternatives?: string[] - installTip?: string | { module: string; label: string }[] + installTip?: string | Array<{ module: string; label: string }> } +// eslint-disable-next-line @typescript-eslint/no-explicit-any const passThru = (action: () => void) => (input: any) => { action() @@ -66,6 +68,7 @@ export class Importer { const req = requireWrapper(name) // remove exports from what we're going to log + // eslint-disable-next-line @typescript-eslint/no-explicit-any const contextReq: any = { ...req } delete contextReq.exports @@ -121,6 +124,7 @@ export class Importer { why: string, moduleName: string, { alternatives = [], installTip = moduleName }: ImportOptions = {}, + // eslint-disable-next-line @typescript-eslint/no-explicit-any ): any { // try to load any of the alternative after trying main one const res = this.tryThese(moduleName, ...alternatives) @@ -163,6 +167,7 @@ export interface RequireResult { exists: E given: string path?: string + // eslint-disable-next-line @typescript-eslint/no-explicit-any exports?: any error?: Error } diff --git a/src/utils/json.ts b/src/utils/json.ts index 289c0fcbde..8fd975c65e 100644 --- a/src/utils/json.ts +++ b/src/utils/json.ts @@ -7,11 +7,13 @@ export function stringify(input: unknown): string { return input === undefined ? UNDEFINED : stableStringify(input) } +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function parse(input: string): any { return input === UNDEFINED ? undefined : JSON.parse(input) } interface NormalizeOptions { + // eslint-disable-next-line @typescript-eslint/no-explicit-any parse?: (input: string) => any } /** diff --git a/src/utils/jsonable-value.spec.ts b/src/utils/jsonable-value.spec.ts index 928cecc7bc..57b1331047 100644 --- a/src/utils/jsonable-value.spec.ts +++ b/src/utils/jsonable-value.spec.ts @@ -21,6 +21,7 @@ it('should cache the serialized value', () => { }) it('should update the serialized value when updating the value', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const jv = new JsonableValue({ foo: 'bar' } as any) expect(jv.serialized).toBe('{"foo":"bar"}') stringify.mockClear() diff --git a/src/utils/memoize.spec.ts b/src/utils/memoize.spec.ts index 4e73c489c5..474aa49c93 100644 --- a/src/utils/memoize.spec.ts +++ b/src/utils/memoize.spec.ts @@ -1,21 +1,27 @@ import { Memoize } from './memoize' describe('memoize', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const sharedHasher = jest.fn((...args: any[]) => args.join(':')) class Dummy { + // eslint-disable-next-line @typescript-eslint/no-explicit-any _getter = jest.fn(function getter(this: any) { return this.data.getter }) + // eslint-disable-next-line @typescript-eslint/no-explicit-any _method0 = jest.fn(function method0(this: any) { return this.data.method0 }) + // eslint-disable-next-line @typescript-eslint/no-explicit-any _method1 = jest.fn(function method1(this: any, ...args: any[]) { return [this.data.method1, ...args].join(':') }) + // eslint-disable-next-line @typescript-eslint/no-explicit-any _method2 = jest.fn(function method2(this: any, ...args: any[]) { return [this.data.method2, ...args].join(':') }) + // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(public data: any) {} @Memoize() @@ -29,11 +35,13 @@ describe('memoize', () => { } @Memoize() + // eslint-disable-next-line @typescript-eslint/no-explicit-any method1(...args: any[]) { return this._method1(...args) } @Memoize(sharedHasher) + // eslint-disable-next-line @typescript-eslint/no-explicit-any method2(...args: any[]) { return this._method2(...args) } diff --git a/src/utils/memoize.ts b/src/utils/memoize.ts index 07266d5f2e..caaf8ff4b1 100644 --- a/src/utils/memoize.ts +++ b/src/utils/memoize.ts @@ -1,12 +1,15 @@ +// eslint-disable-next-line @typescript-eslint/no-explicit-any const cacheProp = Symbol.for('[memoize]') as any /** * @internal */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function Memoize(keyBuilder?: (...args: any[]) => any) { - /* eslint-disable-next-line @typescript-eslint/ban-types */ - return (_: object, propertyKey: string, descriptor: TypedPropertyDescriptor): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return (_: Record, propertyKey: string, descriptor: TypedPropertyDescriptor): void => { if (descriptor.value != null) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any descriptor.value = memoize(propertyKey, descriptor.value, keyBuilder || ((v: any) => v)) } else if (descriptor.get != null) { descriptor.get = memoize(propertyKey, descriptor.get, keyBuilder || (() => propertyKey)) @@ -15,10 +18,11 @@ export function Memoize(keyBuilder?: (...args: any[]) => any) { } // See https://github.com/microsoft/TypeScript/issues/1863#issuecomment-579541944 -/* eslint-disable-next-line @typescript-eslint/ban-types */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any function ensureCache & { [key: string]: any }>( target: T, reset = false, + // eslint-disable-next-line @typescript-eslint/no-explicit-any ): { [key in keyof T]?: Map } { if (reset || !target[cacheProp]) { Object.defineProperty(target, cacheProp, { @@ -31,29 +35,37 @@ function ensureCache & { [key: string]: any }> } // See https://github.com/microsoft/TypeScript/issues/1863#issuecomment-579541944 -/* eslint-disable-next-line @typescript-eslint/ban-types */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any function ensureChildCache & { [key: string]: any }>( target: T, key: keyof T, reset = false, + // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Map { const dict = ensureCache(target) if (reset || !dict[key]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any dict[key] = new Map() } + // eslint-disable-next-line @typescript-eslint/no-explicit-any return dict[key] as Map } function memoize( namespace: string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any func: (...args: any[]) => any, + // eslint-disable-next-line @typescript-eslint/no-explicit-any keyBuilder: (...args: any[]) => any, + // eslint-disable-next-line @typescript-eslint/no-explicit-any ): (...args: any[]) => any { + // eslint-disable-next-line @typescript-eslint/no-explicit-any return function (this: any, ...args: any[]): any { const cache = ensureChildCache(this, namespace) const key = keyBuilder.apply(this, args) if (cache.has(key)) return cache.get(key) + // eslint-disable-next-line @typescript-eslint/no-explicit-any const res: any = func.apply(this, args) cache.set(key, res) diff --git a/src/utils/messages.ts b/src/utils/messages.ts index 40f85fdd77..4fe9460a99 100644 --- a/src/utils/messages.ts +++ b/src/utils/messages.ts @@ -50,6 +50,7 @@ export const enum ImportReasons { /** * @internal */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function interpolate(msg: string, vars: Record = {}): string { // eslint-disable-next-line no-useless-escape return msg.replace(/\{\{([^\}]+)\}\}/g, (_, key) => (key in vars ? vars[key] : _)) diff --git a/src/utils/testing.ts b/src/utils/testing.ts index 4f1fb7e4d2..52ba296ecb 100644 --- a/src/utils/testing.ts +++ b/src/utils/testing.ts @@ -1,7 +1,10 @@ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type MockableFunction = (...args: any[]) => any export type MethodKeysOf = { [K in keyof T]: T[K] extends MockableFunction ? K : never }[keyof T] export type PropertyKeysOf = { [K in keyof T]: T[K] extends MockableFunction ? never : K }[keyof T] +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type ArgumentsOf = T extends (...args: infer A) => any ? A : never +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type ConstructorArgumentsOf = T extends new (...args: infer A) => any ? A : never export interface MockWithArgs extends jest.MockInstance, ArgumentsOf> { @@ -9,6 +12,7 @@ export interface MockWithArgs extends jest.MockInsta (...args: ArgumentsOf): ReturnType } +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type MaybeMockedConstructor = T extends new (...args: any[]) => infer R ? jest.MockInstance> : T @@ -35,5 +39,6 @@ export function mocked(item: T, deep?: false): MaybeMocked export function mocked(item: T, deep: true): MaybeMockedDeep // eslint-disable-next-line no-redeclare export function mocked(item: T, _deep = false): MaybeMocked | MaybeMockedDeep { + // eslint-disable-next-line @typescript-eslint/no-explicit-any return item as any } diff --git a/src/utils/version-checkers.spec.ts b/src/utils/version-checkers.spec.ts index 5f994124ac..f19a44666f 100644 --- a/src/utils/version-checkers.spec.ts +++ b/src/utils/version-checkers.spec.ts @@ -23,6 +23,7 @@ function describeChecker( checker: VersionChecker, moduleName: string, supportedVersions: string[], + // eslint-disable-next-line @typescript-eslint/no-explicit-any unsupportedVersions: any[], ) { describe(moduleName, () => {