Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: use unknown in catch variables where possible #11948

Merged
merged 2 commits into from Oct 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions .eslintrc.js
Expand Up @@ -37,6 +37,10 @@ module.exports = {
rules: {
'@typescript-eslint/array-type': ['error', {default: 'generic'}],
'@typescript-eslint/ban-types': 'error',
'@typescript-eslint/no-implicit-any-catch': [
'error',
{allowExplicitAny: true},
],
'@typescript-eslint/no-unused-vars': [
'error',
{argsIgnorePattern: '^_'},
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/detectOpenHandles.ts
Expand Up @@ -11,7 +11,7 @@ import runJest, {runContinuous} from '../runJest';

try {
require('async_hooks');
} catch (e) {
} catch (e: any) {
if (e.code === 'MODULE_NOT_FOUND') {
// eslint-disable-next-line jest/no-focused-tests
fit('skip test for unsupported nodes', () => {
Expand Down
4 changes: 2 additions & 2 deletions e2e/__tests__/jsonReporter.test.ts
Expand Up @@ -30,7 +30,7 @@ describe('JSON Reporter', () => {

try {
jsonResult = JSON.parse(testOutput);
} catch (err) {
} catch (err: any) {
throw new Error(
`Can't parse the JSON result from ${outputFileName}, ${err.toString()}`,
);
Expand Down Expand Up @@ -71,7 +71,7 @@ describe('JSON Reporter', () => {

try {
jsonResult = JSON.parse(result.stdout);
} catch (err) {
} catch (err: any) {
throw new Error(
"Can't parse the JSON result from stdout" + err.toString(),
);
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/resolveConditions.test.ts
Expand Up @@ -26,7 +26,7 @@ onNodeVersions('>=12.16.0', () => {
});
try {
expect(exitCode).toBe(0);
} catch (error) {
} catch (error: unknown) {
console.log(`Test failed on iteration ${i + 1}`);
throw error;
}
Expand Down
6 changes: 3 additions & 3 deletions e2e/__tests__/testRetries.test.ts
Expand Up @@ -50,7 +50,7 @@ describe('Test Retries', () => {

try {
jsonResult = JSON.parse(testOutput);
} catch (err) {
} catch (err: any) {
throw new Error(
`Can't parse the JSON result from ${outputFileName}, ${err.toString()}`,
);
Expand Down Expand Up @@ -81,7 +81,7 @@ describe('Test Retries', () => {

try {
jsonResult = JSON.parse(testOutput);
} catch (err) {
} catch (err: any) {
throw new Error(
`Can't parse the JSON result from ${outputFileName}, ${err.toString()}`,
);
Expand Down Expand Up @@ -112,7 +112,7 @@ describe('Test Retries', () => {

try {
jsonResult = JSON.parse(testOutput);
} catch (err) {
} catch (err: any) {
throw new Error(
`Can't parse the JSON result from ${outputFileName}, ${err.toString()}`,
);
Expand Down
2 changes: 1 addition & 1 deletion e2e/runJest.ts
Expand Up @@ -144,7 +144,7 @@ export const json = function (
...result,
json: JSON.parse(result.stdout || ''),
};
} catch (e) {
} catch (e: any) {
throw new Error(
`
Can't parse JSON.
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/src/__tests__/isError.test.ts
Expand Up @@ -43,7 +43,7 @@ describe('isError', () => {
testErrorFromDifferentContext((win: Window) => {
try {
win.document.querySelectorAll('');
} catch (e) {
} catch (e: unknown) {
return e;
}
return null;
Expand Down
6 changes: 3 additions & 3 deletions packages/expect/src/__tests__/stacktrace.test.ts
Expand Up @@ -33,7 +33,7 @@ jestExpect.extend({
it('stack trace points to correct location when using matchers', () => {
try {
jestExpect(true).toBe(false);
} catch (error) {
} catch (error: any) {
expect(error.stack).toContain('stacktrace.test.ts:35');
}
});
Expand All @@ -43,7 +43,7 @@ it('stack trace points to correct location when using nested matchers', () => {
jestExpect(true).toMatchPredicate((value: unknown) => {
jestExpect(value).toBe(false);
});
} catch (error) {
} catch (error: any) {
expect(error.stack).toContain('stacktrace.test.ts:44');
}
});
Expand All @@ -59,7 +59,7 @@ it('stack trace points to correct location when throwing from a custom matcher',

foo();
}).toCustomMatch('bar');
} catch (error) {
} catch (error: any) {
expect(error.stack).toContain('stacktrace.test.ts:57');
}
});
2 changes: 1 addition & 1 deletion packages/expect/src/index.ts
Expand Up @@ -349,7 +349,7 @@ const makeThrowingMatcher = (

return processResult(syncResult);
}
} catch (error) {
} catch (error: any) {
return handleError(error);
}
};
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/src/toThrowMatchers.ts
Expand Up @@ -107,7 +107,7 @@ export const createMatcher = (
} else {
try {
received();
} catch (e) {
} catch (e: unknown) {
thrown = getThrown(e);
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-changed-files/src/git.ts
Expand Up @@ -19,7 +19,7 @@ const findChangedFilesUsingCommand = async (

try {
result = await execa('git', args, {cwd});
} catch (e) {
} catch (e: any) {
// TODO: Should we keep the original `message`?
e.message = e.stderr;

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-changed-files/src/hg.ts
Expand Up @@ -32,7 +32,7 @@ const adapter: SCMAdapter = {

try {
result = await execa('hg', args, {cwd, env});
} catch (e) {
} catch (e: any) {
// TODO: Should we keep the original `message`?
e.message = e.stderr;

Expand Down
4 changes: 2 additions & 2 deletions packages/jest-circus/src/run.ts
Expand Up @@ -157,7 +157,7 @@ const _callCircusHook = async ({
timeout,
});
await dispatch({describeBlock, hook, name: 'hook_success', test});
} catch (error) {
} catch (error: unknown) {
await dispatch({describeBlock, error, hook, name: 'hook_failure', test});
}
};
Expand All @@ -180,7 +180,7 @@ const _callCircusTest = async (
timeout,
});
await dispatch({name: 'test_fn_success', test});
} catch (error) {
} catch (error: unknown) {
await dispatch({error, name: 'test_fn_failure', test});
}
};
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-circus/src/utils.ts
Expand Up @@ -253,7 +253,7 @@ export const callAsyncCircusFn = (
} else {
try {
returnedValue = fn.call(testContext);
} catch (error) {
} catch (error: unknown) {
reject(error);
return;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-cli/src/cli/index.ts
Expand Up @@ -34,7 +34,7 @@ export async function run(

const {results, globalConfig} = await runCLI(argv, projects);
readResultsAndExit(results, globalConfig);
} catch (error) {
} catch (error: any) {
clearLine(process.stderr);
clearLine(process.stdout);
if (error?.stack) {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-config/src/__tests__/normalize.test.ts
Expand Up @@ -1816,7 +1816,7 @@ describe('extensionsToTreatAsEsm', () => {

try {
await callback();
} catch (error) {
} catch (error: any) {
expect(wrap(stripAnsi(error.message).trim())).toMatchSnapshot();
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-config/src/normalize.ts
Expand Up @@ -65,7 +65,7 @@ function verifyDirectoryExists(path: Config.Path, key: string) {
)} option is not a directory.`,
);
}
} catch (err) {
} catch (err: any) {
if (err instanceof ValidationError) {
throw err;
}
Expand Down Expand Up @@ -150,7 +150,7 @@ const setupPreset = async (
} catch {}

preset = await requireOrImportModule(presetModule);
} catch (error) {
} catch (error: any) {
if (error instanceof SyntaxError || error instanceof TypeError) {
throw createConfigError(
` Preset ${chalk.bold(presetPath)} is invalid:\n\n ${
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-config/src/readConfigFileAndSetRootDir.ts
Expand Up @@ -36,7 +36,7 @@ export default async function readConfigFileAndSetRootDir(
} else {
configObject = await requireOrImportModule<any>(configPath);
}
} catch (error) {
} catch (error: unknown) {
if (isJSON) {
throw new Error(
`Jest: Failed to parse config file ${configPath}\n` +
Expand Down Expand Up @@ -92,7 +92,7 @@ const loadTSConfigFile = async (
module: 'CommonJS',
},
});
} catch (e) {
} catch (e: any) {
if (e.code === 'MODULE_NOT_FOUND') {
throw new Error(
`Jest: 'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${e.message}`,
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-console/src/BufferedConsole.ts
Expand Up @@ -74,7 +74,7 @@ export default class BufferedConsole extends Console {
assert(value: unknown, message?: string | Error): void {
try {
assert(value, message);
} catch (error) {
} catch (error: any) {
this._log('assert', error.toString());
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-console/src/CustomConsole.ts
Expand Up @@ -52,7 +52,7 @@ export default class CustomConsole extends Console {
assert(value: unknown, message?: string | Error): asserts value {
try {
assert(value, message);
} catch (error) {
} catch (error: any) {
this._logError('assert', error.toString());
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-core/src/TestScheduler.ts
Expand Up @@ -286,7 +286,7 @@ class TestScheduler {
);
}
}
} catch (error) {
} catch (error: unknown) {
if (!watcher.isInterrupted()) {
throw error;
}
Expand Down Expand Up @@ -410,7 +410,7 @@ class TestScheduler {
try {
const Reporter = await requireOrImportModule<any>(path, true);
this.addReporter(new Reporter(this._globalConfig, options));
} catch (error) {
} catch (error: any) {
error.message =
'An error occurred while adding the reporter at path "' +
chalk.bold(path) +
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-core/src/cli/index.ts
Expand Up @@ -168,14 +168,14 @@ const _run10000 = async (
let filter: Filter | undefined;
if (globalConfig.filter && !globalConfig.skipFilter) {
const rawFilter = require(globalConfig.filter);
let filterSetupPromise: Promise<Error | undefined> | undefined;
let filterSetupPromise: Promise<unknown | undefined> | undefined;
if (rawFilter.setup) {
// Wrap filter setup Promise to avoid "uncaught Promise" error.
// If an error is returned, we surface it in the return value.
filterSetupPromise = (async () => {
try {
await rawFilter.setup();
} catch (err) {
} catch (err: unknown) {
return err;
}
return undefined;
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-core/src/runGlobalHook.ts
Expand Up @@ -58,7 +58,7 @@ export default async ({
await globalModule(globalConfig);
},
);
} catch (error) {
} catch (error: unknown) {
if (util.types.isNativeError(error)) {
error.message = `Jest: Got error running ${moduleName} - ${modulePath}, reason: ${error.message}`;

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-core/src/watch.ts
Expand Up @@ -200,7 +200,7 @@ export default async function watch(
stdin,
stdout: outputStream,
});
} catch (error) {
} catch (error: any) {
const errorWithContext = new Error(
`Failed to initialize watch plugin "${chalk.bold(
slash(path.relative(process.cwd(), pluginWithConfig.path)),
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-each/src/bind.ts
Expand Up @@ -50,7 +50,7 @@ export default <EachCallback extends Global.TestCallback>(
timeout,
),
);
} catch (e) {
} catch (e: any) {
const error = new ErrorWithStack(e.message, eachBind);
return cb(title, () => {
throw error;
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-fake-timers/src/legacyFakeTimers.ts
Expand Up @@ -308,7 +308,7 @@ export default class FakeTimers<TimerRef> {
let errThrown = false;
try {
cb();
} catch (e) {
} catch (e: unknown) {
errThrown = true;
cbErr = e;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-haste-map/src/index.ts
Expand Up @@ -793,7 +793,7 @@ export default class HasteMap extends EventEmitter {

try {
return crawl(crawlerOptions).catch(retry);
} catch (error) {
} catch (error: any) {
return retry(error);
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-haste-map/src/worker.ts
Expand Up @@ -60,7 +60,7 @@ export async function worker(data: WorkerMessage): Promise<WorkerMetadata> {
id = fileData.name;
module = [relativeFilePath, H.PACKAGE];
}
} catch (err) {
} catch (err: any) {
throw new Error(`Cannot parse ${filePath} as JSON: ${err.message}`);
}
} else if (!blacklist.has(filePath.substr(filePath.lastIndexOf('.')))) {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/PCancelable.ts
Expand Up @@ -75,7 +75,7 @@ export default class PCancelable<T> implements PromiseLike<T> {
if (typeof this._cancel === 'function') {
try {
this._cancel();
} catch (err) {
} catch (err: unknown) {
this._reject(err);
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/jasmine/Env.ts
Expand Up @@ -438,7 +438,7 @@ export default function (j$: Jasmine) {
let describeReturnValue: unknown | Error;
try {
describeReturnValue = specDefinitions.call(suite);
} catch (e) {
} catch (e: any) {
declarationError = e;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/jasmineAsyncInstall.ts
Expand Up @@ -212,7 +212,7 @@ function makeConcurrent(
`Jest: concurrent test "${spec.getFullName()}" must return a Promise.`,
);
});
} catch (error) {
} catch (error: unknown) {
promise = Promise.reject(error);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/queueRunner.ts
Expand Up @@ -55,7 +55,7 @@ export default function queueRunner(options: Options): PromiseLike<void> & {
};
try {
fn.call(options.userContext, next);
} catch (e) {
} catch (e: any) {
options.onException(e);
resolve();
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-leak-detector/src/index.ts
Expand Up @@ -33,7 +33,7 @@ export default class {
try {
// eslint-disable-next-line import/no-extraneous-dependencies
weak = require('weak-napi');
} catch (err) {
} catch (err: any) {
if (!err || err.code !== 'MODULE_NOT_FOUND') {
throw err;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-mock/src/index.ts
Expand Up @@ -595,7 +595,7 @@ export class ModuleMocker {

return undefined;
})();
} catch (error) {
} catch (error: unknown) {
// Store the thrown error so we can record it, then re-throw it.
thrownError = error;
callDidThrowError = true;
Expand Down