Skip to content

Commit 50bab21

Browse files
authored
chore: run eslint with type information on CI (#13368)
1 parent d78baab commit 50bab21

File tree

67 files changed

+320
-171
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+320
-171
lines changed

.github/workflows/nodejs.yml

+2
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ jobs:
5454
run: yarn typecheck:examples
5555
- name: typecheck tests
5656
run: yarn typecheck:tests
57+
- name: run ESLint with type info
58+
run: yarn lint-ts-files
5759

5860
lint:
5961
name: Lint

e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap

+2-2
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ exports[`moduleNameMapper wrong array configuration 1`] = `
4141
12 | module.exports = () => 'test';
4242
13 |
4343
44-
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:896:17)
44+
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:891:17)
4545
at Object.require (index.js:10:1)
4646
at Object.require (__tests__/index.js:10:20)"
4747
`;
@@ -71,7 +71,7 @@ exports[`moduleNameMapper wrong configuration 1`] = `
7171
12 | module.exports = () => 'test';
7272
13 |
7373
74-
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:896:17)
74+
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:891:17)
7575
at Object.require (index.js:10:1)
7676
at Object.require (__tests__/index.js:10:20)"
7777
`;

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@
103103
"lint:prettier-script": "prettier . \"!**/*.{js,jsx,cjs,mjs,ts,tsx}\" --cache",
104104
"lint:prettier": "yarn lint:prettier-script --write",
105105
"lint:prettier:ci": "yarn lint:prettier-script --check",
106+
"lint-ts-files": "node scripts/lintTs.mjs",
106107
"remove-examples": "node ./scripts/remove-examples.mjs",
107108
"test-ci-partial": "yarn test-ci-partial:parallel -i",
108109
"test-ci-partial:parallel": "yarn jest --color --config jest.config.ci.mjs",

packages/babel-jest/src/__tests__/getCacheKey.test.ts

+11-7
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ describe('getCacheKey', () => {
5252
readFileSync: () => 'new this file',
5353
}));
5454

55-
const {createTransformer}: typeof import('../index') = require('../index');
55+
const {createTransformer} =
56+
require('../index') as typeof import('../index');
5657

5758
const newCacheKey = createTransformer().getCacheKey!(
5859
sourceText,
@@ -65,7 +66,7 @@ describe('getCacheKey', () => {
6566

6667
test('if `babelOptions.options` value is changing', () => {
6768
jest.doMock('../loadBabelConfig', () => {
68-
const babel: typeof import('@babel/core') = require('@babel/core');
69+
const babel = require('@babel/core') as typeof import('@babel/core');
6970

7071
return {
7172
loadPartialConfig: (options: BabelTransformOptions) => ({
@@ -75,7 +76,8 @@ describe('getCacheKey', () => {
7576
};
7677
});
7778

78-
const {createTransformer}: typeof import('../index') = require('../index');
79+
const {createTransformer} =
80+
require('../index') as typeof import('../index');
7981

8082
const newCacheKey = createTransformer().getCacheKey!(
8183
sourceText,
@@ -117,7 +119,7 @@ describe('getCacheKey', () => {
117119

118120
test('if `babelOptions.config` value is changing', () => {
119121
jest.doMock('../loadBabelConfig', () => {
120-
const babel: typeof import('@babel/core') = require('@babel/core');
122+
const babel = require('@babel/core') as typeof import('@babel/core');
121123

122124
return {
123125
loadPartialConfig: (options: BabelTransformOptions) => ({
@@ -127,7 +129,8 @@ describe('getCacheKey', () => {
127129
};
128130
});
129131

130-
const {createTransformer}: typeof import('../index') = require('../index');
132+
const {createTransformer} =
133+
require('../index') as typeof import('../index');
131134

132135
const newCacheKey = createTransformer().getCacheKey!(
133136
sourceText,
@@ -140,7 +143,7 @@ describe('getCacheKey', () => {
140143

141144
test('if `babelOptions.babelrc` value is changing', () => {
142145
jest.doMock('../loadBabelConfig', () => {
143-
const babel: typeof import('@babel/core') = require('@babel/core');
146+
const babel = require('@babel/core') as typeof import('@babel/core');
144147

145148
return {
146149
loadPartialConfig: (options: BabelTransformOptions) => ({
@@ -150,7 +153,8 @@ describe('getCacheKey', () => {
150153
};
151154
});
152155

153-
const {createTransformer}: typeof import('../index') = require('../index');
156+
const {createTransformer} =
157+
require('../index') as typeof import('../index');
154158

155159
const newCacheKey = createTransformer().getCacheKey!(
156160
sourceText,

packages/babel-jest/src/__tests__/index.ts

+19-6
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,17 @@ import {makeProjectConfig} from '@jest/test-utils';
1313
import type {TransformOptions} from '@jest/transform';
1414
import babelJest, {createTransformer} from '../index';
1515
import {loadPartialConfig} from '../loadBabelConfig';
16+
1617
jest.mock('../loadBabelConfig', () => {
1718
const actual =
1819
jest.requireActual<typeof import('@babel/core')>('@babel/core');
1920

2021
return {
21-
loadPartialConfig: jest.fn((...args) => actual.loadPartialConfig(...args)),
22-
loadPartialConfigAsync: jest.fn((...args) =>
23-
actual.loadPartialConfigAsync(...args),
22+
loadPartialConfig: jest.fn<typeof actual.loadPartialConfig>((...args) =>
23+
actual.loadPartialConfig(...args),
24+
),
25+
loadPartialConfigAsync: jest.fn<typeof actual.loadPartialConfigAsync>(
26+
(...args) => actual.loadPartialConfigAsync(...args),
2427
),
2528
};
2629
});
@@ -69,7 +72,7 @@ test('Returns source string with inline maps when no transformOptions is passed'
6972
});
7073

7174
test('Returns source string with inline maps when no transformOptions is passed async', async () => {
72-
const result: any = await defaultBabelJestTransformer.processAsync!(
75+
const result = await defaultBabelJestTransformer.processAsync!(
7376
sourceString,
7477
'dummy_path.js',
7578
{
@@ -86,8 +89,18 @@ test('Returns source string with inline maps when no transformOptions is passed
8689
expect(result.map).toBeDefined();
8790
expect(result.code).toMatch('//# sourceMappingURL');
8891
expect(result.code).toMatch('customMultiply');
89-
expect(result.map!.sources).toEqual(['dummy_path.js']);
90-
expect(JSON.stringify(result.map!.sourcesContent)).toMatch('customMultiply');
92+
93+
const {map} = result;
94+
95+
expect(map).toBeTruthy();
96+
expect(typeof map).not.toBe('string');
97+
98+
if (map == null || typeof map === 'string') {
99+
throw new Error('dead code');
100+
}
101+
102+
expect(map.sources).toEqual(['dummy_path.js']);
103+
expect(JSON.stringify(map.sourcesContent)).toMatch('customMultiply');
91104
});
92105

93106
describe('caller option correctly merges from defaults and options', () => {

packages/babel-jest/src/index.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ function addIstanbulInstrumentation(
5151
const copiedBabelOptions: TransformOptions = {...babelOptions};
5252
copiedBabelOptions.auxiliaryCommentBefore = ' istanbul ignore next ';
5353
// Copied from jest-runtime transform.js
54-
copiedBabelOptions.plugins = (copiedBabelOptions.plugins || []).concat([
54+
copiedBabelOptions.plugins = (copiedBabelOptions.plugins ?? []).concat([
5555
[
5656
babelIstanbulPlugin,
5757
{
@@ -76,7 +76,7 @@ function getCacheKeyFromConfig(
7676
): string {
7777
const {config, configString, instrument} = transformOptions;
7878

79-
const configPath = [babelOptions.config || '', babelOptions.babelrc || ''];
79+
const configPath = [babelOptions.config ?? '', babelOptions.babelrc ?? ''];
8080

8181
return createHash('sha256')
8282
.update(THIS_FILE)
@@ -93,9 +93,9 @@ function getCacheKeyFromConfig(
9393
.update('\0', 'utf8')
9494
.update(instrument ? 'instrument' : '')
9595
.update('\0', 'utf8')
96-
.update(process.env.NODE_ENV || '')
96+
.update(process.env.NODE_ENV ?? '')
9797
.update('\0', 'utf8')
98-
.update(process.env.BABEL_ENV || '')
98+
.update(process.env.BABEL_ENV ?? '')
9999
.update('\0', 'utf8')
100100
.update(process.version)
101101
.digest('hex')

packages/babel-plugin-jest-hoist/src/index.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -114,10 +114,10 @@ const IDVisitor = {
114114
],
115115
};
116116

117-
const FUNCTIONS: Record<
117+
const FUNCTIONS = Object.create(null) as Record<
118118
string,
119119
<T extends Node>(args: Array<NodePath<T>>) => boolean
120-
> = Object.create(null);
120+
>;
121121

122122
FUNCTIONS.mock = args => {
123123
if (args.length === 1) {
@@ -142,7 +142,7 @@ FUNCTIONS.mock = args => {
142142
let scope = id.scope;
143143

144144
while (scope !== parentScope) {
145-
if (scope.bindings[name]) {
145+
if (scope.bindings[name] != null) {
146146
found = true;
147147
break;
148148
}

packages/diff-sequences/src/__tests__/index.property.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ const findCommonItems = (a: Array<string>, b: Array<string>): Array<string> => {
2727
const extractCount = (data: Array<string>): Map<string, number> => {
2828
const countPerChar = new Map<string, number>();
2929
for (const item of data) {
30-
const currentCount = countPerChar.get(item) || 0;
30+
const currentCount = countPerChar.get(item) ?? 0;
3131
countPerChar.set(item, currentCount + 1);
3232
}
3333
return countPerChar;
@@ -93,7 +93,7 @@ it('should have at most the same number of each character as its inputs', () =>
9393
const commonCount = extractCount(commonItems);
9494
const aCount = extractCount(a);
9595
for (const [item, count] of commonCount) {
96-
const countOfItemInA = aCount.get(item) || 0;
96+
const countOfItemInA = aCount.get(item) ?? 0;
9797
expect(countOfItemInA).toBeGreaterThanOrEqual(count);
9898
}
9999
}),

packages/diff-sequences/src/__tests__/index.test.ts

+6-3
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ describe('invalid arg', () => {
1515
describe('length', () => {
1616
test('is not a number', () => {
1717
expect(() => {
18-
diff('0' as any, 0, isCommon, foundSubsequence);
18+
// @ts-expect-error: Testing runtime errors here
19+
diff('0', 0, isCommon, foundSubsequence);
1920
}).toThrow(/aLength/);
2021
});
2122
test('Infinity is not a safe integer', () => {
@@ -49,12 +50,14 @@ describe('invalid arg', () => {
4950
describe('callback', () => {
5051
test('null is not a function', () => {
5152
expect(() => {
52-
diff(0, 0, null as any, foundSubsequence);
53+
// @ts-expect-error: Testing runtime errors here
54+
diff(0, 0, null, foundSubsequence);
5355
}).toThrow(/isCommon/);
5456
});
5557
test('undefined is not a function', () => {
5658
expect(() => {
57-
diff(0, 0, isCommon, undefined as any);
59+
// @ts-expect-error: Testing runtime errors here
60+
diff(0, 0, isCommon, undefined);
5861
}).toThrow(/foundSubsequence/);
5962
});
6063
});

packages/expect-utils/src/jasmineUtils.ts

+1-3
Original file line numberDiff line numberDiff line change
@@ -211,9 +211,7 @@ function keys(obj: object, hasKey: (obj: object, key: string) => boolean) {
211211
}
212212
return keys.concat(
213213
(Object.getOwnPropertySymbols(obj) as Array<any>).filter(
214-
symbol =>
215-
(Object.getOwnPropertyDescriptor(obj, symbol) as PropertyDescriptor)
216-
.enumerable,
214+
symbol => Object.getOwnPropertyDescriptor(obj, symbol)!.enumerable,
217215
),
218216
);
219217
}

packages/expect/src/__tests__/toThrowMatchers.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -458,9 +458,9 @@ matchers.forEach(toThrow => {
458458
err = new Err('async apple');
459459
}
460460
if (resolve) {
461-
return await Promise.resolve(err || 'apple');
461+
return Promise.resolve(err || 'apple');
462462
} else {
463-
return await Promise.reject(err || 'apple');
463+
return Promise.reject(err || 'apple');
464464
}
465465
};
466466

packages/expect/src/asymmetricMatchers.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ class StringMatching extends AsymmetricMatcher<RegExp> {
296296
}
297297

298298
class CloseTo extends AsymmetricMatcher<number> {
299-
private precision: number;
299+
private readonly precision: number;
300300

301301
constructor(sample: number, precision = 2, inverse = false) {
302302
if (!isA('Number', sample)) {

packages/expect/src/index.ts

+2-6
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ import toThrowMatchers, {
3939
createMatcher as createThrowMatcher,
4040
} from './toThrowMatchers';
4141
import type {
42-
AsyncExpectationResult,
4342
Expect,
4443
ExpectationResult,
4544
MatcherContext,
@@ -363,19 +362,16 @@ const makeThrowingMatcher = (
363362
})();
364363

365364
if (isPromise(potentialResult)) {
366-
const asyncResult = potentialResult as AsyncExpectationResult;
367365
const asyncError = new JestAssertionError();
368366
if (Error.captureStackTrace) {
369367
Error.captureStackTrace(asyncError, throwingMatcher);
370368
}
371369

372-
return asyncResult
370+
return potentialResult
373371
.then(aResult => processResult(aResult, asyncError))
374372
.catch(handleError);
375373
} else {
376-
const syncResult = potentialResult as SyncExpectationResult;
377-
378-
return processResult(syncResult);
374+
return processResult(potentialResult);
379375
}
380376
} catch (error: any) {
381377
return handleError(error);

packages/jest-config/src/normalize.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ const mergeGlobalsWithPreset = (
108108
options: Config.InitialOptions,
109109
preset: Config.InitialOptions,
110110
) => {
111-
if (options['globals'] && preset['globals']) {
112-
options['globals'] = merge(preset['globals'], options['globals']);
111+
if (options.globals && preset.globals) {
112+
options.globals = merge(preset.globals, options.globals);
113113
}
114114
};
115115

@@ -1061,14 +1061,14 @@ export default async function normalize(
10611061
);
10621062
newOptions.maxWorkers = getMaxWorkers(argv, options);
10631063

1064-
if (newOptions.testRegex!.length && options.testMatch) {
1064+
if (newOptions.testRegex.length > 0 && options.testMatch) {
10651065
throw createConfigError(
10661066
` Configuration options ${chalk.bold('testMatch')} and` +
10671067
` ${chalk.bold('testRegex')} cannot be used together.`,
10681068
);
10691069
}
10701070

1071-
if (newOptions.testRegex!.length && !options.testMatch) {
1071+
if (newOptions.testRegex.length > 0 && !options.testMatch) {
10721072
// Prevent the default testMatch conflicting with any explicitly
10731073
// configured `testRegex` value
10741074
newOptions.testMatch = [];
@@ -1101,7 +1101,7 @@ export default async function normalize(
11011101
if (
11021102
micromatch(
11031103
[replacePathSepForGlob(path.relative(options.rootDir, filename))],
1104-
newOptions.collectCoverageFrom!,
1104+
newOptions.collectCoverageFrom,
11051105
).length === 0
11061106
) {
11071107
return patterns;

packages/jest-config/src/utils.ts

+2-5
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ export const resolve = (
4848
);
4949
}
5050
/// can cast as string since nulls will be thrown
51-
return module as string;
51+
return module!;
5252
};
5353

5454
export const escapeGlobCharacters = (path: string): string =>
@@ -106,10 +106,7 @@ export const _replaceRootDirTags = <T extends ReplaceRootDirConfigValues>(
106106
return config;
107107
}
108108

109-
return _replaceRootDirInObject(
110-
rootDir,
111-
config as ReplaceRootDirConfigObj,
112-
) as T;
109+
return _replaceRootDirInObject(rootDir, config) as T;
113110
case 'string':
114111
return replaceRootDirInPath(rootDir, config) as T;
115112
}

packages/jest-console/src/BufferedConsole.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import type {
1919
} from './types';
2020

2121
export default class BufferedConsole extends Console {
22-
private _buffer: ConsoleBuffer = [];
22+
private readonly _buffer: ConsoleBuffer = [];
2323
private _counters: LogCounters = {};
2424
private _timers: LogTimers = {};
2525
private _groupDepth = 0;

packages/jest-console/src/CustomConsole.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ import type {LogCounters, LogMessage, LogTimers, LogType} from './types';
1515
type Formatter = (type: LogType, message: LogMessage) => string;
1616

1717
export default class CustomConsole extends Console {
18-
private _stdout: NodeJS.WriteStream;
19-
private _stderr: NodeJS.WriteStream;
20-
private _formatBuffer: Formatter;
18+
private readonly _stdout: NodeJS.WriteStream;
19+
private readonly _stderr: NodeJS.WriteStream;
20+
private readonly _formatBuffer: Formatter;
2121
private _counters: LogCounters = {};
2222
private _timers: LogTimers = {};
2323
private _groupDepth = 0;

0 commit comments

Comments
 (0)