Skip to content

Commit

Permalink
chore: lint usage of Arrays (jestjs#14804)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Dec 29, 2023
1 parent eaea490 commit 3054e56
Show file tree
Hide file tree
Showing 38 changed files with 81 additions and 87 deletions.
17 changes: 6 additions & 11 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,12 @@ module.exports = {
// enforced by `@typescript-eslint/no-this-alias` already
'unicorn/no-this-assignment': 'off',

// Not an issue with TypeScript
'unicorn/no-array-callback-reference': 'off',

// reduce is fine
'unicorn/no-array-reduce': 'off',

// nah
'unicorn/consistent-destructuring': 'off',
'unicorn/no-nested-ternary': 'off',
Expand All @@ -676,35 +682,24 @@ module.exports = {

// TODO: decide whether or not we want these
'unicorn/filename-case': 'off',
'unicorn/no-array-callback-reference': 'off',
'unicorn/no-array-reduce': 'off',
'unicorn/prefer-reflect-apply': 'off',

// TODO: turn on at some point
'unicorn/catch-error-name': 'off',
'unicorn/consistent-function-scoping': 'off',
'unicorn/error-message': 'off',
'unicorn/escape-case': 'off',
'unicorn/no-array-method-this-argument': 'off',
'unicorn/no-array-push-push': 'off',
'unicorn/no-await-expression-member': 'off',
'unicorn/no-console-spaces': 'off',
'unicorn/no-empty-file': 'off',
'unicorn/no-for-loop': 'off',
'unicorn/no-hex-escape': 'off',
'unicorn/no-instanceof-array': 'off',
'unicorn/no-new-array': 'off',
'unicorn/no-object-as-default-parameter': 'off',
'unicorn/no-thenable': 'off',
'unicorn/no-typeof-undefined': 'off',
'unicorn/no-useless-promise-resolve-reject': 'off',
'unicorn/no-useless-undefined': 'off',
'unicorn/number-literal-case': 'off',
'unicorn/prefer-array-flat': 'off',
'unicorn/prefer-array-flat-map': 'off',
'unicorn/prefer-array-index-of': 'off',
'unicorn/prefer-array-some': 'off',
'unicorn/prefer-at': 'off',
'unicorn/prefer-date-now': 'off',
'unicorn/prefer-logical-operator-over-ternary': 'off',
'unicorn/prefer-math-trunc': 'off',
Expand Down
2 changes: 1 addition & 1 deletion e2e/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ const sortTests = (stdout: string) =>
if (['RUNS', 'PASS', 'FAIL'].includes(line.slice(0, 4))) {
tests.push([line]);
} else {
tests[tests.length - 1].push(line);
tests.at(-1)!.push(line);
}
return tests;
}, [])
Expand Down
2 changes: 1 addition & 1 deletion e2e/babel-plugin-jest-hoist/__tests__/integration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ jest.mock('../__test_modules__/f', () => {
fn: () => {
// The `jest.mock` transform will allow require, built-ins and globals.
const path = require('path');
const array = new Array(3);
const array = Array.from({length: 3});
array[0] = path.sep;
return jest.fn(() => array);
},
Expand Down
2 changes: 1 addition & 1 deletion packages/expect-utils/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ const isObject = (a: any) => a !== null && typeof a === 'object';
const isObjectWithKeys = (a: any) =>
isObject(a) &&
!(a instanceof Error) &&
!(a instanceof Array) &&
!Array.isArray(a) &&
!(a instanceof Date);

export const subsetEquality = (
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-circus/src/__tests__/shuffleArray.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ describe('rngBuilder', () => {
// Some people will be using seeds relying on a particular order
test.each([1, 2, 4, 8, 16])('creates a randomizer given seed %s', seed => {
const rng = rngBuilder(seed);
const results = new Array(10).fill(0).map(() => rng.next(0, 10));
const results = Array.from({length: 10}).map(() => rng.next(0, 10));
expect(results).toMatchSnapshot();
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export const runAndTransformResultsToJestFormat = async ({
retryReasons: testResult.retryReasons,
startAt: testResult.startedAt,
status,
title: testResult.testPath[testResult.testPath.length - 1],
title: testResult.testPath.at(-1)!,
};
},
);
Expand Down
5 changes: 2 additions & 3 deletions packages/jest-circus/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -401,8 +401,7 @@ const makeTestResults = (
const child = currentBlock.children[i];

if (child.type === 'describeBlock') {
stack.push([currentBlock, i + 1]);
stack.push([child, 0]);
stack.push([currentBlock, i + 1], [child, 0]);
break;
}
if (child.type === 'test') {
Expand Down Expand Up @@ -478,7 +477,7 @@ const resolveTestCaseStartInfo = (
name => name !== ROOT_DESCRIBE_BLOCK_NAME,
);
const fullName = ancestorTitles.join(' ');
const title = testNamesPath[testNamesPath.length - 1];
const title = testNamesPath.at(-1)!;
// remove title
ancestorTitles.pop();
return {
Expand Down
8 changes: 3 additions & 5 deletions packages/jest-config/src/__tests__/resolveConfigPath.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,9 @@ describe.each(JEST_CONFIG_EXT_ORDER.slice(0))(
);

const pickPairsWithSameOrder = <T>(array: ReadonlyArray<T>) =>
array
.map((value1, idx, arr) =>
arr.slice(idx + 1).map(value2 => [value1, value2]),
)
.flat();
array.flatMap((value1, idx, arr) =>
arr.slice(idx + 1).map(value2 => [value1, value2]),
);

test('pickPairsWithSameOrder', () => {
expect(pickPairsWithSameOrder([1, 2, 3])).toStrictEqual([
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-config/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,9 +231,9 @@ const ensureNoDuplicateConfigs = (
String(configPath),
)}:
Project 1: ${chalk.bold(projects[parsedConfigs.findIndex(x => x === config)])}
Project 1: ${chalk.bold(projects[parsedConfigs.indexOf(config)])}
Project 2: ${chalk.bold(
projects[parsedConfigs.findIndex(x => x === configPathMap.get(configPath))],
projects[parsedConfigs.indexOf(configPathMap.get(configPath))],
)}
This usually means that your ${chalk.bold(
Expand Down
40 changes: 20 additions & 20 deletions packages/jest-core/src/__tests__/testSchedulerHelper.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,26 +23,26 @@ const getTestMock = () => ({
const getTestsMock = () => [getTestMock(), getTestMock()];

test.each`
tests | timings | detectOpenHandles | runInBand | maxWorkers | watch | workerIdleMemoryLimit | expectedResult
${[getTestMock()]} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${true} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${2} | ${true} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${true} | ${1} | ${true} | ${undefined} | ${true}
${[getTestMock()]} | ${[2000, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${undefined} | ${false}
${getTestMock()} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${false} | ${undefined} | ${true}
${getTestMock()} | ${[2000, 500]} | ${false} | ${false} | ${2} | ${false} | ${undefined} | ${false}
${[getTestMock()]} | ${[2000]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${true}
${getTestsMock()} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${true}
${new Array(45)} | ${[500]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${true} | ${false} | ${undefined} | ${false} | ${undefined} | ${true}
${[getTestMock()]} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${'500MB'} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${true} | ${'500MB'} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${false} | ${'500MB'} | ${false}
${[getTestMock()]} | ${[2000]} | ${false} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${false}
${getTestsMock()} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${true} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${true}
tests | timings | detectOpenHandles | runInBand | maxWorkers | watch | workerIdleMemoryLimit | expectedResult
${[getTestMock()]} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${true} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${2} | ${true} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${true} | ${1} | ${true} | ${undefined} | ${true}
${[getTestMock()]} | ${[2000, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${undefined} | ${false}
${getTestMock()} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${false} | ${undefined} | ${true}
${getTestMock()} | ${[2000, 500]} | ${false} | ${false} | ${2} | ${false} | ${undefined} | ${false}
${[getTestMock()]} | ${[2000]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${true}
${getTestsMock()} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${true}
${Array.from({length: 45})} | ${[500]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${true} | ${false} | ${undefined} | ${false} | ${undefined} | ${true}
${[getTestMock()]} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${'500MB'} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${true} | ${'500MB'} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${false} | ${'500MB'} | ${false}
${[getTestMock()]} | ${[2000]} | ${false} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${false}
${getTestsMock()} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${false}
${getTestsMock()} | ${[2000, 500]} | ${true} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${true}
`(
'shouldRunInBand() - should return $expectedResult for runInBand mode',
({
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-core/src/__tests__/watch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ describe('Watch mode flows', () => {

// We need the penultimate call as Jest forces a final call to restore
// updateSnapshot because it's not sticky after a run…?
const lastCall = updateGlobalConfig.mock.calls.slice(-2)[0];
const lastCall = updateGlobalConfig.mock.calls.at(-2);
// eslint-disable-next-line jest/valid-expect
let expector = expect(lastCall[1]);
if (!ok) {
Expand Down
4 changes: 3 additions & 1 deletion packages/jest-core/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,9 @@ const buildContextsAndHasteMaps = async (
globalConfig: Config.GlobalConfig,
outputStream: WriteStream,
) => {
const hasteMapInstances = new Array(configs.length);
const hasteMapInstances = Array.from<IHasteMap>({
length: configs.length,
});
const contexts = await Promise.all(
configs.map(async (config, index) => {
createDirectory(config.cacheDirectory);
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-core/src/runJest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ export default async function runJest({
);
}),
)
).reduce((total, paths) => total.concat(paths), []);
).flat();
testSchedulerContext.sourcesRelatedToTestsInChangedFiles = new Set(
sourcesRelatedToTestsInChangedFilesArray,
);
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-fake-timers/src/legacyFakeTimers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ export default class FakeTimers<TimerRef = unknown> {

this._timerAPIs.setImmediate(() => {
if (!this._disposed) {
if (this._immediates.find(x => x.uuid === uuid)) {
if (this._immediates.some(x => x.uuid === uuid)) {
try {
callback.apply(null, args);
} finally {
Expand Down
3 changes: 1 addition & 2 deletions packages/jest-haste-map/src/crawlers/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,7 @@ function findNative(
if (index) {
args.push('-o');
}
args.push('-iname');
args.push(`*.${ext}`);
args.push('-iname', `*.${ext}`);
}
if (extensions.length > 0) {
args.push(')');
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-haste-map/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,7 @@ class HasteMap extends EventEmitter implements IHasteMap {
.then(() => {
// If we get duplicate events for the same file, ignore them.
if (
eventsQueue.find(
eventsQueue.some(
event =>
event.type === type &&
event.filePath === filePath &&
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-haste-map/src/watchers/NodeWatcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ module.exports = class NodeWatcher extends EventEmitter {
let closest = {mtime: 0};
let c = 0;
// eslint-disable-next-line unicorn/no-array-for-each
Object.keys(this.dirRegistery[dir]).forEach(function (file, i, arr) {
Object.keys(this.dirRegistery[dir]).forEach((file, i, arr) => {
fs.lstat(path.join(dir, file), (error, stat) => {
if (found) {
return;
Expand All @@ -242,7 +242,7 @@ module.exports = class NodeWatcher extends EventEmitter {
}
}
});
}, this);
});
}

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/jest-haste-map/src/watchers/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ exports.isFileIncluded = function (globs, dot, doIgnore, relativePath) {
}
return globs.length > 0
? micromatch.some(relativePath, globs, {dot})
: dot || micromatch.some(relativePath, '**/*');
: // eslint-disable-next-line unicorn/no-array-method-this-argument
dot || micromatch.some(relativePath, '**/*');
};

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/jasmine/CallTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class CallTracker {
};

this.mostRecent = function () {
return calls[calls.length - 1];
return calls.at(-1)!;
};

this.reset = function () {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/jasmine/Env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export default function jasmineEnv(j$: Jasmine) {
let currentDeclarationSuite = topSuite;

const currentSuite = function () {
return currentlyExecutingSuites[currentlyExecutingSuites.length - 1];
return currentlyExecutingSuites.at(-1)!;
};

const currentRunnable = function () {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-matcher-utils/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ describe('stringify()', () => {
test('reduces maxWidth if stringifying very large arrays', () => {
const big: any = [];
const small: any = [];
const testString = new Array(1000).join('x');
const testString = Array.from({length: 1000}).join('x');

for (let i = 0; i < 100; i += 1) {
big[i] = testString;
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-mock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ export class ModuleMocker {
this._mockState.set(f, state);
}
if (state.calls.length > 0) {
state.lastCall = state.calls[state.calls.length - 1];
state.lastCall = state.calls.at(-1);
}
return state;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-reporters/src/GitHubActionsReporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ export default class GitHubActionsReporter extends BaseReporter {
): ResultTreeNode {
const node: ResultTreeNode = {
children: [],
name: ancestors[ancestors.length - 1],
name: ancestors.at(-1)!,
passed: true,
};
const branches: Array<Array<string>> = [];
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-reporters/src/SummaryReporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export default class SummaryReporter extends BaseReporter {
): void {
const {numTotalTestSuites, testResults, wasInterrupted} = aggregatedResults;
if (numTotalTestSuites) {
const lastResult = testResults[testResults.length - 1];
const lastResult = testResults.at(-1);
// Print a newline if the last test did not fail to line up newlines
// similar to when an error would have been thrown in the test.
if (
Expand Down
8 changes: 4 additions & 4 deletions packages/jest-reporters/src/__tests__/SummaryReporter.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ test('snapshots needs update with npm test', () => {
unmatched: 2,
},
startTime: 0,
testResults: {},
testResults: [],
};

process.env.npm_config_user_agent = 'npm';
Expand All @@ -78,7 +78,7 @@ test('snapshots needs update with yarn test', () => {
unmatched: 2,
},
startTime: 0,
testResults: {},
testResults: [],
};

process.env.npm_config_user_agent = 'yarn';
Expand Down Expand Up @@ -116,7 +116,7 @@ test('snapshots all have results (no update)', () => {
updated: 1,
},
startTime: 0,
testResults: {},
testResults: [],
};

requireReporter();
Expand Down Expand Up @@ -153,7 +153,7 @@ test('snapshots all have results (after update)', () => {
updated: 1,
},
startTime: 0,
testResults: {},
testResults: [],
};

requireReporter();
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-resolve/src/__tests__/resolve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,7 @@ describe('nodeModulesPaths', () => {
it('provides custom module paths after node_modules', () => {
const src = require.resolve('../');
const result = nodeModulesPaths(src, {paths: ['./customFolder']});
expect(result[result.length - 1]).toBe('./customFolder');
expect(result.at(-1)).toBe('./customFolder');
});

it('provides custom module multy paths after node_modules', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-resolve/src/nodeModulesPaths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default function nodeModulesPaths(

const paths: Array<string> = [physicalBasedir];
let parsed = path.parse(physicalBasedir);
while (parsed.dir !== paths[paths.length - 1]) {
while (parsed.dir !== paths.at(-1)) {
paths.push(parsed.dir);
parsed = path.parse(parsed.dir);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-resolve/src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ export default class Resolver {

const moduleDirectory = this._options.moduleDirectories;
const paths = nodeModulesPaths(from, {moduleDirectory});
if (paths[paths.length - 1] === undefined) {
if (paths.at(-1) === undefined) {
// circumvent node-resolve bug that adds `undefined` as last item.
paths.pop();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ describe('Runtime requireModule', () => {
expect(exports.paths.length).toBeGreaterThan(0);
const root = path.parse(process.cwd()).root;
const globalPath = path.join(root, 'node_modules');
const rootIndex = exports.paths.findIndex(path => path === globalPath);
const rootIndex = exports.paths.indexOf(globalPath);
for (const [index, path] of exports.paths.entries()) {
if (index <= rootIndex) {
expect(moduleDirectories.some(dir => path.endsWith(dir))).toBe(true);
Expand Down
Loading

0 comments on commit 3054e56

Please sign in to comment.