Skip to content

Commit

Permalink
chore: enable a bunch more lint rules (jestjs#14794)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Dec 29, 2023
1 parent 175665e commit 0469b4c
Show file tree
Hide file tree
Showing 39 changed files with 144 additions and 115 deletions.
30 changes: 22 additions & 8 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,19 @@ module.exports = {
'plugin:eslint-comments/recommended',
'plugin:prettier/recommended',
'plugin:unicorn/recommended',
'plugin:promise/recommended',
],
globals: {
console: 'readonly',
},
overrides: [
{
extends: ['plugin:@typescript-eslint/strict', 'plugin:import/typescript'],
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/strict',
'plugin:@typescript-eslint/stylistic',
'plugin:import/typescript',
],
files: ['*.ts', '*.tsx'],
plugins: ['@typescript-eslint/eslint-plugin', 'local'],
rules: {
Expand All @@ -59,6 +65,7 @@ module.exports = {
],
'@typescript-eslint/prefer-ts-expect-error': 'error',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/consistent-indexed-object-style': 'off',
// TS verifies these
'consistent-return': 'off',
'no-dupe-class-members': 'off',
Expand All @@ -68,10 +75,7 @@ module.exports = {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-invalid-void-type': 'off',

// TODO: part of "stylistic" rules, remove explicit activation when that lands
'@typescript-eslint/no-empty-function': 'error',
'@typescript-eslint/no-empty-interface': 'error',
'@typescript-eslint/consistent-type-definitions': 'off',

// not needed to be enforced for TS
'import/namespace': 'off',
Expand Down Expand Up @@ -326,6 +330,7 @@ module.exports = {
rules: {
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/class-literal-property-style': 'off',
},
},
{
Expand Down Expand Up @@ -427,6 +432,12 @@ module.exports = {
'unicorn/no-static-only-class': 'off',
},
},
{
files: '**/*.mjs',
rules: {
'unicorn/prefer-top-level-await': 'error',
},
},
],
parser: '@typescript-eslint/parser',
parserOptions: {
Expand Down Expand Up @@ -617,6 +628,11 @@ module.exports = {
'prefer-arrow-callback': ['error', {allowNamedFunctions: true}],
'prefer-const': 'error',
'prefer-template': 'error',

'promise/always-return': 'off',
'promise/catch-or-return': 'off',
'promise/no-callback-in-promise': 'off',

quotes: [
'error',
'single',
Expand Down Expand Up @@ -655,10 +671,8 @@ module.exports = {
'unicorn/prefer-event-target': 'off',
'unicorn/prefer-switch': 'off',
'unicorn/prefer-ternary': 'off',
'unicorn/switch-case-braces': 'off',

// TODO: enable for `.mjs` files
'unicorn/prefer-top-level-await': 'off',
'unicorn/switch-case-braces': 'off',

// TODO: decide whether or not we want these
'unicorn/filename-case': 'off',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
'use strict';

it.concurrent('Good Test', async () => {
await new Promise(r => setTimeout(r, 100));
await new Promise(resolve => setTimeout(resolve, 100));
});

it.concurrent('Bad Test', async () => {
Expand Down
2 changes: 1 addition & 1 deletion e2e/snapshot-concurrent/__tests__/works.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/
'use strict';

const sleep = ms => new Promise(r => setTimeout(r, ms));
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

describe('A', () => {
it.concurrent('a', async () => {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"eslint-plugin-local": "link:./.eslintplugin",
"eslint-plugin-markdown": "^3.0.0",
"eslint-plugin-prettier": "^5.0.0",
"eslint-plugin-promise": "^6.1.1",
"eslint-plugin-unicorn": "^50.0.0",
"execa": "^5.0.0",
"find-process": "^1.4.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-plugin-jest-hoist/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ FUNCTIONS.mock = args => {
);
}

const ids: Set<NodePath<Identifier>> = new Set();
const ids = new Set<NodePath<Identifier>>();
const parentScope = moduleFactory.parentPath.scope;
// @ts-expect-error: ReferencedIdentifier and denylist are not known on visitors
moduleFactory.traverse(IDVisitor, {ids});
Expand Down
9 changes: 2 additions & 7 deletions packages/expect-utils/src/jasmineUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,8 @@ function eq(
}

const testerContext: TesterContext = {equals};
for (let i = 0; i < customTesters.length; i++) {
const customTesterResult = customTesters[i].call(
testerContext,
a,
b,
customTesters,
);
for (const item of customTesters) {
const customTesterResult = item.call(testerContext, a, b, customTesters);
if (customTesterResult !== undefined) {
return customTesterResult;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/expect/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ const makeResolveMatcher =
)}\n\n` +
'Received promise rejected instead of resolved\n' +
`Rejected to value: ${matcherUtils.printReceived(reason)}`;
return Promise.reject(outerErr);
throw outerErr;
},
);
};
Expand Down Expand Up @@ -254,7 +254,7 @@ const makeRejectMatcher =
)}\n\n` +
'Received promise resolved instead of rejected\n' +
`Resolved to value: ${matcherUtils.printReceived(result)}`;
return Promise.reject(outerErr);
throw outerErr;
},
reason =>
makeThrowingMatcher(matcher, isNot, 'rejects', reason, innerErr).apply(
Expand Down
9 changes: 4 additions & 5 deletions packages/expect/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,10 @@ export interface BaseExpect {
setState(state: Partial<MatcherState>): void;
}

export type Expect = {
<T = unknown>(
actual: T,
): Matchers<void, T> & Inverse<Matchers<void, T>> & PromiseMatchers<T>;
} & BaseExpect &
export type Expect = (<T = unknown>(
actual: T,
) => Matchers<void, T> & Inverse<Matchers<void, T>> & PromiseMatchers<T>) &
BaseExpect &
AsymmetricMatchers &
Inverse<Omit<AsymmetricMatchers, 'any' | 'anything'>>;

Expand Down
10 changes: 6 additions & 4 deletions packages/jest-core/src/__tests__/collectHandles.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ describe('collectHandles', () => {
const server = http.createServer((_, response) => response.end('ok'));

// Start and stop server.
await new Promise(r => server.listen(0, r));
await new Promise(r => server.close(r));
await new Promise(resolve => server.listen(0, resolve));
await new Promise(resolve => server.close(resolve));

const openHandles = await handleCollector();
expect(openHandles).toHaveLength(0);
Expand All @@ -130,11 +130,13 @@ describe('collectHandles', () => {
// creates a long-lived `TCPSERVERWRAP` resource. We want to make sure we
// capture that long-lived resource.
const server = new http.Server();
await new Promise(r => server.listen({host: 'localhost', port: 0}, r));
await new Promise(resolve =>
server.listen({host: 'localhost', port: 0}, resolve),
);

const openHandles = await handleCollector();

await new Promise(r => server.close(r));
await new Promise(resolve => server.close(resolve));

expect(openHandles).toContainEqual(
expect.objectContaining({message: 'TCPSERVERWRAP'}),
Expand Down
6 changes: 4 additions & 2 deletions packages/jest-core/src/__tests__/watch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const regularUpdateGlobalConfig = require('../lib/updateGlobalConfig').default;
const updateGlobalConfig = jest.fn(regularUpdateGlobalConfig);
jest.doMock('../lib/updateGlobalConfig', () => updateGlobalConfig);

const nextTick = () => new Promise(res => process.nextTick(res));
const nextTick = () => new Promise(resolve => process.nextTick(resolve));

beforeAll(() => {
jest.spyOn(process, 'on').mockImplementation(() => {});
Expand Down Expand Up @@ -771,7 +771,9 @@ describe('Watch mode flows', () => {

it('prevents Jest from handling keys when active and returns control when end is called', async () => {
let resolveShowPrompt;
const run = jest.fn(() => new Promise(res => (resolveShowPrompt = res)));
const run = jest.fn(
() => new Promise(resolve => (resolveShowPrompt = resolve)),
);
const pluginPath = `${__dirname}/__fixtures__/plugin_path_1`;
jest.doMock(
pluginPath,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ jest.doMock(

const watch = require('../watch').default;

const nextTick = () => new Promise(res => process.nextTick(res));
const nextTick = () => new Promise(resolve => process.nextTick(resolve));

const globalConfig = {
rootDir: '',
Expand Down
6 changes: 3 additions & 3 deletions packages/jest-core/src/plugins/TestNamePattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class TestNamePatternPlugin extends BaseWatchPlugin {
globalConfig: Config.GlobalConfig,
updateConfigAndRun: UpdateConfigCallback,
): Promise<void> {
return new Promise((res, rej) => {
return new Promise((resolve, reject) => {
const testNamePatternPrompt = new TestNamePatternPrompt(
this._stdout,
this._prompt,
Expand All @@ -50,9 +50,9 @@ class TestNamePatternPlugin extends BaseWatchPlugin {
testNamePatternPrompt.run(
(value: string) => {
updateConfigAndRun({mode: 'watch', testNamePattern: value});
res();
resolve();
},
rej,
reject,
{
header: activeFilters(globalConfig),
},
Expand Down
6 changes: 3 additions & 3 deletions packages/jest-core/src/plugins/TestPathPattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class TestPathPatternPlugin extends BaseWatchPlugin {
globalConfig: Config.GlobalConfig,
updateConfigAndRun: UpdateConfigCallback,
): Promise<void> {
return new Promise((res, rej) => {
return new Promise((resolve, reject) => {
const testPathPatternPrompt = new TestPathPatternPrompt(
this._stdout,
this._prompt,
Expand All @@ -50,9 +50,9 @@ class TestPathPatternPlugin extends BaseWatchPlugin {
testPathPatternPrompt.run(
(value: string) => {
updateConfigAndRun({mode: 'watch', testPathPatterns: [value]});
res();
resolve();
},
rej,
reject,
{
header: activeFilters(globalConfig),
},
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-core/src/plugins/UpdateSnapshotsInteractive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class UpdateSnapshotInteractivePlugin extends BaseWatchPlugin {
updateConfigAndRun: Function,
): Promise<void> {
if (this._failedSnapshotTestAssertions.length > 0) {
return new Promise(res => {
return new Promise(resolve => {
this._snapshotInteractiveMode.run(
this._failedSnapshotTestAssertions,
(assertion, shouldUpdateSnapshot) => {
Expand All @@ -79,7 +79,7 @@ class UpdateSnapshotInteractivePlugin extends BaseWatchPlugin {
updateSnapshot: shouldUpdateSnapshot ? 'all' : 'none',
});
if (!this._snapshotInteractiveMode.isActive()) {
res();
resolve();
}
},
);
Expand Down
5 changes: 3 additions & 2 deletions packages/jest-docblock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ export function extract(contents: string): string {
}

export function strip(contents: string): string {
const match = contents.match(docblockRe);
return match && match[0] ? contents.slice(match[0].length) : contents;
const matchResult = contents.match(docblockRe);
const match = matchResult?.[0];
return match == null ? contents : contents.slice(match.length);
}

export function parse(docblock: string): Pragmas {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-haste-map/src/blacklist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
//
// Feel free to add any extensions that cannot be a Haste module.

const extensions: Set<string> = new Set([
const extensions = new Set<string>([
// JSONs are never haste modules, except for "package.json", which is handled.
'.json',

Expand Down
6 changes: 3 additions & 3 deletions packages/jest-jasmine2/src/jasmine/CallTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ class CallTracker {
};

this.allArgs = function () {
const callArgs = [];
for (let i = 0; i < calls.length; i++) {
callArgs.push(calls[i].args);
const callArgs: Array<unknown> = [];
for (const call of calls) {
callArgs.push(call.args);
}

return callArgs;
Expand Down
6 changes: 2 additions & 4 deletions packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ export default class ReportDispatcher implements Reporter {
constructor(methods: Array<keyof Reporter>) {
const dispatchedMethods = methods || [];

for (let i = 0; i < dispatchedMethods.length; i++) {
const method = dispatchedMethods[i];
for (const method of dispatchedMethods) {
this[method] = (function (m) {
return function () {
dispatch(m, arguments);
Expand Down Expand Up @@ -86,8 +85,7 @@ export default class ReportDispatcher implements Reporter {
if (reporters.length === 0 && fallbackReporter !== null) {
reporters.push(fallbackReporter);
}
for (let i = 0; i < reporters.length; i++) {
const reporter = reporters[i];
for (const reporter of reporters) {
if (reporter[method]) {
// @ts-expect-error: wrong context
reporter[method].apply(reporter, args);
Expand Down
6 changes: 2 additions & 4 deletions packages/jest-jasmine2/src/jasmine/Suite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,7 @@ export default class Suite {
};
this.result.failedExpectations.push(expectationResultFactory(data));
} else {
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
for (const child of this.children) {
child.onException.apply(child, args);
}
}
Expand All @@ -205,8 +204,7 @@ export default class Suite {
throw new ExpectationFailed();
}
} else {
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
for (const child of this.children) {
try {
child.addExpectationResult.apply(child, args);
} catch {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const isMap = (value: any): value is Map<unknown, unknown> =>

export default function deepCyclicCopyReplaceable<T>(
value: T,
cycles: WeakMap<any, any> = new WeakMap(),
cycles = new WeakMap<any, any>(),
): T {
if (typeof value !== 'object' || value === null) {
return value;
Expand Down
4 changes: 1 addition & 3 deletions packages/jest-mock/__typetests__/Mocked.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,7 @@ interface SomeFunctionObject {
one: {
(oneA: number, oneB?: boolean): boolean;
more: {
time: {
(time: number): void;
};
time: (time: number) => void;
};
};
}
Expand Down
Loading

0 comments on commit 0469b4c

Please sign in to comment.