Skip to content

Commit

Permalink
chore: run eslint with type information on CI (#13368)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Oct 3, 2022
1 parent d78baab commit 50bab21
Show file tree
Hide file tree
Showing 67 changed files with 320 additions and 171 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ jobs:
run: yarn typecheck:examples
- name: typecheck tests
run: yarn typecheck:tests
- name: run ESLint with type info
run: yarn lint-ts-files

lint:
name: Lint
Expand Down
4 changes: 2 additions & 2 deletions e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ exports[`moduleNameMapper wrong array configuration 1`] = `
12 | module.exports = () => 'test';
13 |
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:896:17)
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:891:17)
at Object.require (index.js:10:1)
at Object.require (__tests__/index.js:10:20)"
`;
Expand Down Expand Up @@ -71,7 +71,7 @@ exports[`moduleNameMapper wrong configuration 1`] = `
12 | module.exports = () => 'test';
13 |
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:896:17)
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/resolver.js:891:17)
at Object.require (index.js:10:1)
at Object.require (__tests__/index.js:10:20)"
`;
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
"lint:prettier-script": "prettier . \"!**/*.{js,jsx,cjs,mjs,ts,tsx}\" --cache",
"lint:prettier": "yarn lint:prettier-script --write",
"lint:prettier:ci": "yarn lint:prettier-script --check",
"lint-ts-files": "node scripts/lintTs.mjs",
"remove-examples": "node ./scripts/remove-examples.mjs",
"test-ci-partial": "yarn test-ci-partial:parallel -i",
"test-ci-partial:parallel": "yarn jest --color --config jest.config.ci.mjs",
Expand Down
18 changes: 11 additions & 7 deletions packages/babel-jest/src/__tests__/getCacheKey.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ describe('getCacheKey', () => {
readFileSync: () => 'new this file',
}));

const {createTransformer}: typeof import('../index') = require('../index');
const {createTransformer} =
require('../index') as typeof import('../index');

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

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

return {
loadPartialConfig: (options: BabelTransformOptions) => ({
Expand All @@ -75,7 +76,8 @@ describe('getCacheKey', () => {
};
});

const {createTransformer}: typeof import('../index') = require('../index');
const {createTransformer} =
require('../index') as typeof import('../index');

const newCacheKey = createTransformer().getCacheKey!(
sourceText,
Expand Down Expand Up @@ -117,7 +119,7 @@ describe('getCacheKey', () => {

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

return {
loadPartialConfig: (options: BabelTransformOptions) => ({
Expand All @@ -127,7 +129,8 @@ describe('getCacheKey', () => {
};
});

const {createTransformer}: typeof import('../index') = require('../index');
const {createTransformer} =
require('../index') as typeof import('../index');

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

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

return {
loadPartialConfig: (options: BabelTransformOptions) => ({
Expand All @@ -150,7 +153,8 @@ describe('getCacheKey', () => {
};
});

const {createTransformer}: typeof import('../index') = require('../index');
const {createTransformer} =
require('../index') as typeof import('../index');

const newCacheKey = createTransformer().getCacheKey!(
sourceText,
Expand Down
25 changes: 19 additions & 6 deletions packages/babel-jest/src/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ import {makeProjectConfig} from '@jest/test-utils';
import type {TransformOptions} from '@jest/transform';
import babelJest, {createTransformer} from '../index';
import {loadPartialConfig} from '../loadBabelConfig';

jest.mock('../loadBabelConfig', () => {
const actual =
jest.requireActual<typeof import('@babel/core')>('@babel/core');

return {
loadPartialConfig: jest.fn((...args) => actual.loadPartialConfig(...args)),
loadPartialConfigAsync: jest.fn((...args) =>
actual.loadPartialConfigAsync(...args),
loadPartialConfig: jest.fn<typeof actual.loadPartialConfig>((...args) =>
actual.loadPartialConfig(...args),
),
loadPartialConfigAsync: jest.fn<typeof actual.loadPartialConfigAsync>(
(...args) => actual.loadPartialConfigAsync(...args),
),
};
});
Expand Down Expand Up @@ -69,7 +72,7 @@ test('Returns source string with inline maps when no transformOptions is passed'
});

test('Returns source string with inline maps when no transformOptions is passed async', async () => {
const result: any = await defaultBabelJestTransformer.processAsync!(
const result = await defaultBabelJestTransformer.processAsync!(
sourceString,
'dummy_path.js',
{
Expand All @@ -86,8 +89,18 @@ test('Returns source string with inline maps when no transformOptions is passed
expect(result.map).toBeDefined();
expect(result.code).toMatch('//# sourceMappingURL');
expect(result.code).toMatch('customMultiply');
expect(result.map!.sources).toEqual(['dummy_path.js']);
expect(JSON.stringify(result.map!.sourcesContent)).toMatch('customMultiply');

const {map} = result;

expect(map).toBeTruthy();
expect(typeof map).not.toBe('string');

if (map == null || typeof map === 'string') {
throw new Error('dead code');
}

expect(map.sources).toEqual(['dummy_path.js']);
expect(JSON.stringify(map.sourcesContent)).toMatch('customMultiply');
});

describe('caller option correctly merges from defaults and options', () => {
Expand Down
8 changes: 4 additions & 4 deletions packages/babel-jest/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function addIstanbulInstrumentation(
const copiedBabelOptions: TransformOptions = {...babelOptions};
copiedBabelOptions.auxiliaryCommentBefore = ' istanbul ignore next ';
// Copied from jest-runtime transform.js
copiedBabelOptions.plugins = (copiedBabelOptions.plugins || []).concat([
copiedBabelOptions.plugins = (copiedBabelOptions.plugins ?? []).concat([
[
babelIstanbulPlugin,
{
Expand All @@ -76,7 +76,7 @@ function getCacheKeyFromConfig(
): string {
const {config, configString, instrument} = transformOptions;

const configPath = [babelOptions.config || '', babelOptions.babelrc || ''];
const configPath = [babelOptions.config ?? '', babelOptions.babelrc ?? ''];

return createHash('sha256')
.update(THIS_FILE)
Expand All @@ -93,9 +93,9 @@ function getCacheKeyFromConfig(
.update('\0', 'utf8')
.update(instrument ? 'instrument' : '')
.update('\0', 'utf8')
.update(process.env.NODE_ENV || '')
.update(process.env.NODE_ENV ?? '')
.update('\0', 'utf8')
.update(process.env.BABEL_ENV || '')
.update(process.env.BABEL_ENV ?? '')
.update('\0', 'utf8')
.update(process.version)
.digest('hex')
Expand Down
6 changes: 3 additions & 3 deletions packages/babel-plugin-jest-hoist/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,10 @@ const IDVisitor = {
],
};

const FUNCTIONS: Record<
const FUNCTIONS = Object.create(null) as Record<
string,
<T extends Node>(args: Array<NodePath<T>>) => boolean
> = Object.create(null);
>;

FUNCTIONS.mock = args => {
if (args.length === 1) {
Expand All @@ -142,7 +142,7 @@ FUNCTIONS.mock = args => {
let scope = id.scope;

while (scope !== parentScope) {
if (scope.bindings[name]) {
if (scope.bindings[name] != null) {
found = true;
break;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/diff-sequences/src/__tests__/index.property.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const findCommonItems = (a: Array<string>, b: Array<string>): Array<string> => {
const extractCount = (data: Array<string>): Map<string, number> => {
const countPerChar = new Map<string, number>();
for (const item of data) {
const currentCount = countPerChar.get(item) || 0;
const currentCount = countPerChar.get(item) ?? 0;
countPerChar.set(item, currentCount + 1);
}
return countPerChar;
Expand Down Expand Up @@ -93,7 +93,7 @@ it('should have at most the same number of each character as its inputs', () =>
const commonCount = extractCount(commonItems);
const aCount = extractCount(a);
for (const [item, count] of commonCount) {
const countOfItemInA = aCount.get(item) || 0;
const countOfItemInA = aCount.get(item) ?? 0;
expect(countOfItemInA).toBeGreaterThanOrEqual(count);
}
}),
Expand Down
9 changes: 6 additions & 3 deletions packages/diff-sequences/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ describe('invalid arg', () => {
describe('length', () => {
test('is not a number', () => {
expect(() => {
diff('0' as any, 0, isCommon, foundSubsequence);
// @ts-expect-error: Testing runtime errors here
diff('0', 0, isCommon, foundSubsequence);
}).toThrow(/aLength/);
});
test('Infinity is not a safe integer', () => {
Expand Down Expand Up @@ -49,12 +50,14 @@ describe('invalid arg', () => {
describe('callback', () => {
test('null is not a function', () => {
expect(() => {
diff(0, 0, null as any, foundSubsequence);
// @ts-expect-error: Testing runtime errors here
diff(0, 0, null, foundSubsequence);
}).toThrow(/isCommon/);
});
test('undefined is not a function', () => {
expect(() => {
diff(0, 0, isCommon, undefined as any);
// @ts-expect-error: Testing runtime errors here
diff(0, 0, isCommon, undefined);
}).toThrow(/foundSubsequence/);
});
});
Expand Down
4 changes: 1 addition & 3 deletions packages/expect-utils/src/jasmineUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,7 @@ function keys(obj: object, hasKey: (obj: object, key: string) => boolean) {
}
return keys.concat(
(Object.getOwnPropertySymbols(obj) as Array<any>).filter(
symbol =>
(Object.getOwnPropertyDescriptor(obj, symbol) as PropertyDescriptor)
.enumerable,
symbol => Object.getOwnPropertyDescriptor(obj, symbol)!.enumerable,
),
);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/expect/src/__tests__/toThrowMatchers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,9 +458,9 @@ matchers.forEach(toThrow => {
err = new Err('async apple');
}
if (resolve) {
return await Promise.resolve(err || 'apple');
return Promise.resolve(err || 'apple');
} else {
return await Promise.reject(err || 'apple');
return Promise.reject(err || 'apple');
}
};

Expand Down
2 changes: 1 addition & 1 deletion packages/expect/src/asymmetricMatchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ class StringMatching extends AsymmetricMatcher<RegExp> {
}

class CloseTo extends AsymmetricMatcher<number> {
private precision: number;
private readonly precision: number;

constructor(sample: number, precision = 2, inverse = false) {
if (!isA('Number', sample)) {
Expand Down
8 changes: 2 additions & 6 deletions packages/expect/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ import toThrowMatchers, {
createMatcher as createThrowMatcher,
} from './toThrowMatchers';
import type {
AsyncExpectationResult,
Expect,
ExpectationResult,
MatcherContext,
Expand Down Expand Up @@ -363,19 +362,16 @@ const makeThrowingMatcher = (
})();

if (isPromise(potentialResult)) {
const asyncResult = potentialResult as AsyncExpectationResult;
const asyncError = new JestAssertionError();
if (Error.captureStackTrace) {
Error.captureStackTrace(asyncError, throwingMatcher);
}

return asyncResult
return potentialResult
.then(aResult => processResult(aResult, asyncError))
.catch(handleError);
} else {
const syncResult = potentialResult as SyncExpectationResult;

return processResult(syncResult);
return processResult(potentialResult);
}
} catch (error: any) {
return handleError(error);
Expand Down
10 changes: 5 additions & 5 deletions packages/jest-config/src/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ const mergeGlobalsWithPreset = (
options: Config.InitialOptions,
preset: Config.InitialOptions,
) => {
if (options['globals'] && preset['globals']) {
options['globals'] = merge(preset['globals'], options['globals']);
if (options.globals && preset.globals) {
options.globals = merge(preset.globals, options.globals);
}
};

Expand Down Expand Up @@ -1061,14 +1061,14 @@ export default async function normalize(
);
newOptions.maxWorkers = getMaxWorkers(argv, options);

if (newOptions.testRegex!.length && options.testMatch) {
if (newOptions.testRegex.length > 0 && options.testMatch) {
throw createConfigError(
` Configuration options ${chalk.bold('testMatch')} and` +
` ${chalk.bold('testRegex')} cannot be used together.`,
);
}

if (newOptions.testRegex!.length && !options.testMatch) {
if (newOptions.testRegex.length > 0 && !options.testMatch) {
// Prevent the default testMatch conflicting with any explicitly
// configured `testRegex` value
newOptions.testMatch = [];
Expand Down Expand Up @@ -1101,7 +1101,7 @@ export default async function normalize(
if (
micromatch(
[replacePathSepForGlob(path.relative(options.rootDir, filename))],
newOptions.collectCoverageFrom!,
newOptions.collectCoverageFrom,
).length === 0
) {
return patterns;
Expand Down
7 changes: 2 additions & 5 deletions packages/jest-config/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const resolve = (
);
}
/// can cast as string since nulls will be thrown
return module as string;
return module!;
};

export const escapeGlobCharacters = (path: string): string =>
Expand Down Expand Up @@ -106,10 +106,7 @@ export const _replaceRootDirTags = <T extends ReplaceRootDirConfigValues>(
return config;
}

return _replaceRootDirInObject(
rootDir,
config as ReplaceRootDirConfigObj,
) as T;
return _replaceRootDirInObject(rootDir, config) as T;
case 'string':
return replaceRootDirInPath(rootDir, config) as T;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-console/src/BufferedConsole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type {
} from './types';

export default class BufferedConsole extends Console {
private _buffer: ConsoleBuffer = [];
private readonly _buffer: ConsoleBuffer = [];
private _counters: LogCounters = {};
private _timers: LogTimers = {};
private _groupDepth = 0;
Expand Down
6 changes: 3 additions & 3 deletions packages/jest-console/src/CustomConsole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ import type {LogCounters, LogMessage, LogTimers, LogType} from './types';
type Formatter = (type: LogType, message: LogMessage) => string;

export default class CustomConsole extends Console {
private _stdout: NodeJS.WriteStream;
private _stderr: NodeJS.WriteStream;
private _formatBuffer: Formatter;
private readonly _stdout: NodeJS.WriteStream;
private readonly _stderr: NodeJS.WriteStream;
private readonly _formatBuffer: Formatter;
private _counters: LogCounters = {};
private _timers: LogTimers = {};
private _groupDepth = 0;
Expand Down
Loading

0 comments on commit 50bab21

Please sign in to comment.