diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 75ce0a7f3bd3..c06d9390ba68 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -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', @@ -676,8 +682,6 @@ 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 @@ -685,26 +689,17 @@ module.exports = { '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', diff --git a/e2e/Utils.ts b/e2e/Utils.ts index 083cd8dc261a..11f542a22e8b 100644 --- a/e2e/Utils.ts +++ b/e2e/Utils.ts @@ -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; }, []) diff --git a/e2e/babel-plugin-jest-hoist/__tests__/integration.test.js b/e2e/babel-plugin-jest-hoist/__tests__/integration.test.js index 9f4c7a6773c7..452cf03855e2 100644 --- a/e2e/babel-plugin-jest-hoist/__tests__/integration.test.js +++ b/e2e/babel-plugin-jest-hoist/__tests__/integration.test.js @@ -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); }, diff --git a/packages/expect-utils/src/utils.ts b/packages/expect-utils/src/utils.ts index cf3ff2aec4d5..dc4250fe5bbc 100644 --- a/packages/expect-utils/src/utils.ts +++ b/packages/expect-utils/src/utils.ts @@ -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 = ( diff --git a/packages/jest-circus/src/__tests__/shuffleArray.test.ts b/packages/jest-circus/src/__tests__/shuffleArray.test.ts index 890f741801d9..99b1b693f3a6 100644 --- a/packages/jest-circus/src/__tests__/shuffleArray.test.ts +++ b/packages/jest-circus/src/__tests__/shuffleArray.test.ts @@ -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(); }); }); diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts index dcb25bb15a61..a26db7e15494 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts @@ -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)!, }; }, ); diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts index 12e6e9595293..eefd51feac4e 100644 --- a/packages/jest-circus/src/utils.ts +++ b/packages/jest-circus/src/utils.ts @@ -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') { @@ -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 { diff --git a/packages/jest-config/src/__tests__/resolveConfigPath.test.ts b/packages/jest-config/src/__tests__/resolveConfigPath.test.ts index a1d9b51a1987..cd4667473bbb 100644 --- a/packages/jest-config/src/__tests__/resolveConfigPath.test.ts +++ b/packages/jest-config/src/__tests__/resolveConfigPath.test.ts @@ -182,11 +182,9 @@ describe.each(JEST_CONFIG_EXT_ORDER.slice(0))( ); const pickPairsWithSameOrder = (array: ReadonlyArray) => - 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([ diff --git a/packages/jest-config/src/index.ts b/packages/jest-config/src/index.ts index 8d27b8fcc6b9..b63d731f0d72 100644 --- a/packages/jest-config/src/index.ts +++ b/packages/jest-config/src/index.ts @@ -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( diff --git a/packages/jest-core/src/__tests__/testSchedulerHelper.test.js b/packages/jest-core/src/__tests__/testSchedulerHelper.test.js index 945add3f9497..710ee23867ab 100644 --- a/packages/jest-core/src/__tests__/testSchedulerHelper.test.js +++ b/packages/jest-core/src/__tests__/testSchedulerHelper.test.js @@ -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', ({ diff --git a/packages/jest-core/src/__tests__/watch.test.js b/packages/jest-core/src/__tests__/watch.test.js index 41e565d5f6df..8dc175f789c3 100644 --- a/packages/jest-core/src/__tests__/watch.test.js +++ b/packages/jest-core/src/__tests__/watch.test.js @@ -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) { diff --git a/packages/jest-core/src/cli/index.ts b/packages/jest-core/src/cli/index.ts index a8f341000779..d89812411a64 100644 --- a/packages/jest-core/src/cli/index.ts +++ b/packages/jest-core/src/cli/index.ts @@ -145,7 +145,9 @@ const buildContextsAndHasteMaps = async ( globalConfig: Config.GlobalConfig, outputStream: WriteStream, ) => { - const hasteMapInstances = new Array(configs.length); + const hasteMapInstances = Array.from({ + length: configs.length, + }); const contexts = await Promise.all( configs.map(async (config, index) => { createDirectory(config.cacheDirectory); diff --git a/packages/jest-core/src/runJest.ts b/packages/jest-core/src/runJest.ts index 620b4f4427a0..d60c5e6012b1 100644 --- a/packages/jest-core/src/runJest.ts +++ b/packages/jest-core/src/runJest.ts @@ -284,7 +284,7 @@ export default async function runJest({ ); }), ) - ).reduce((total, paths) => total.concat(paths), []); + ).flat(); testSchedulerContext.sourcesRelatedToTestsInChangedFiles = new Set( sourcesRelatedToTestsInChangedFilesArray, ); diff --git a/packages/jest-fake-timers/src/legacyFakeTimers.ts b/packages/jest-fake-timers/src/legacyFakeTimers.ts index a1954c0e93e3..4e6818b09834 100644 --- a/packages/jest-fake-timers/src/legacyFakeTimers.ts +++ b/packages/jest-fake-timers/src/legacyFakeTimers.ts @@ -513,7 +513,7 @@ export default class FakeTimers { 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 { diff --git a/packages/jest-haste-map/src/crawlers/node.ts b/packages/jest-haste-map/src/crawlers/node.ts index 6628fff9c8e9..f06dcb86a760 100644 --- a/packages/jest-haste-map/src/crawlers/node.ts +++ b/packages/jest-haste-map/src/crawlers/node.ts @@ -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(')'); diff --git a/packages/jest-haste-map/src/index.ts b/packages/jest-haste-map/src/index.ts index 4457b9790208..aecf09321c7a 100644 --- a/packages/jest-haste-map/src/index.ts +++ b/packages/jest-haste-map/src/index.ts @@ -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 && diff --git a/packages/jest-haste-map/src/watchers/NodeWatcher.js b/packages/jest-haste-map/src/watchers/NodeWatcher.js index b1c58f17e4d5..a8ec9b67be1f 100644 --- a/packages/jest-haste-map/src/watchers/NodeWatcher.js +++ b/packages/jest-haste-map/src/watchers/NodeWatcher.js @@ -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; @@ -242,7 +242,7 @@ module.exports = class NodeWatcher extends EventEmitter { } } }); - }, this); + }); } /** diff --git a/packages/jest-haste-map/src/watchers/common.js b/packages/jest-haste-map/src/watchers/common.js index 883e613f57e7..b5062e9dabc1 100644 --- a/packages/jest-haste-map/src/watchers/common.js +++ b/packages/jest-haste-map/src/watchers/common.js @@ -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, '**/*'); }; /** diff --git a/packages/jest-jasmine2/src/jasmine/CallTracker.ts b/packages/jest-jasmine2/src/jasmine/CallTracker.ts index 0409d71d2344..27f804ccb184 100644 --- a/packages/jest-jasmine2/src/jasmine/CallTracker.ts +++ b/packages/jest-jasmine2/src/jasmine/CallTracker.ts @@ -84,7 +84,7 @@ class CallTracker { }; this.mostRecent = function () { - return calls[calls.length - 1]; + return calls.at(-1)!; }; this.reset = function () { diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index c3c1e0cf75c8..c97eb4b1adcf 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -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 () { diff --git a/packages/jest-matcher-utils/src/__tests__/index.test.ts b/packages/jest-matcher-utils/src/__tests__/index.test.ts index 0605e1de5e4c..229f82741dd8 100644 --- a/packages/jest-matcher-utils/src/__tests__/index.test.ts +++ b/packages/jest-matcher-utils/src/__tests__/index.test.ts @@ -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; diff --git a/packages/jest-mock/src/index.ts b/packages/jest-mock/src/index.ts index 7b786d3af4ed..dc17fe1ed769 100644 --- a/packages/jest-mock/src/index.ts +++ b/packages/jest-mock/src/index.ts @@ -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; } diff --git a/packages/jest-reporters/src/GitHubActionsReporter.ts b/packages/jest-reporters/src/GitHubActionsReporter.ts index be3990ae0752..ae168b92e6ff 100644 --- a/packages/jest-reporters/src/GitHubActionsReporter.ts +++ b/packages/jest-reporters/src/GitHubActionsReporter.ts @@ -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> = []; diff --git a/packages/jest-reporters/src/SummaryReporter.ts b/packages/jest-reporters/src/SummaryReporter.ts index 9a34e1cb7a9f..06f6383384a7 100644 --- a/packages/jest-reporters/src/SummaryReporter.ts +++ b/packages/jest-reporters/src/SummaryReporter.ts @@ -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 ( diff --git a/packages/jest-reporters/src/__tests__/SummaryReporter.test.js b/packages/jest-reporters/src/__tests__/SummaryReporter.test.js index 6ace91cd6c5f..115e36382e24 100644 --- a/packages/jest-reporters/src/__tests__/SummaryReporter.test.js +++ b/packages/jest-reporters/src/__tests__/SummaryReporter.test.js @@ -53,7 +53,7 @@ test('snapshots needs update with npm test', () => { unmatched: 2, }, startTime: 0, - testResults: {}, + testResults: [], }; process.env.npm_config_user_agent = 'npm'; @@ -78,7 +78,7 @@ test('snapshots needs update with yarn test', () => { unmatched: 2, }, startTime: 0, - testResults: {}, + testResults: [], }; process.env.npm_config_user_agent = 'yarn'; @@ -116,7 +116,7 @@ test('snapshots all have results (no update)', () => { updated: 1, }, startTime: 0, - testResults: {}, + testResults: [], }; requireReporter(); @@ -153,7 +153,7 @@ test('snapshots all have results (after update)', () => { updated: 1, }, startTime: 0, - testResults: {}, + testResults: [], }; requireReporter(); diff --git a/packages/jest-resolve/src/__tests__/resolve.test.ts b/packages/jest-resolve/src/__tests__/resolve.test.ts index d728fe2d073d..0c557816bf41 100644 --- a/packages/jest-resolve/src/__tests__/resolve.test.ts +++ b/packages/jest-resolve/src/__tests__/resolve.test.ts @@ -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', () => { diff --git a/packages/jest-resolve/src/nodeModulesPaths.ts b/packages/jest-resolve/src/nodeModulesPaths.ts index c9ebc0f7e460..bccadae34025 100644 --- a/packages/jest-resolve/src/nodeModulesPaths.ts +++ b/packages/jest-resolve/src/nodeModulesPaths.ts @@ -47,7 +47,7 @@ export default function nodeModulesPaths( const paths: Array = [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); } diff --git a/packages/jest-resolve/src/resolver.ts b/packages/jest-resolve/src/resolver.ts index e4be68f5fdb0..0280b826033d 100644 --- a/packages/jest-resolve/src/resolver.ts +++ b/packages/jest-resolve/src/resolver.ts @@ -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(); } diff --git a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js index 1d38f0eefafb..c1492f0bc896 100644 --- a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js +++ b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js @@ -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); diff --git a/packages/jest-snapshot/src/dedentLines.ts b/packages/jest-snapshot/src/dedentLines.ts index 7ac07c05be2e..4efc5e89cd86 100644 --- a/packages/jest-snapshot/src/dedentLines.ts +++ b/packages/jest-snapshot/src/dedentLines.ts @@ -114,7 +114,7 @@ const dedentMarkup = (input: Array, output: Array): boolean => { return false; // because text has more than one adjacent line } - const indentationLengthOfTag = stack[stack.length - 1]; + const indentationLengthOfTag = stack.at(-1)!; output.push(line.slice(indentationLengthOfTag + 2)); isText = true; } diff --git a/packages/jest-snapshot/src/index.ts b/packages/jest-snapshot/src/index.ts index b210f9fbca9b..75d4c9290581 100644 --- a/packages/jest-snapshot/src/index.ts +++ b/packages/jest-snapshot/src/index.ts @@ -83,7 +83,7 @@ function stripAddedIndentation(inlineSnapshot: string) { return inlineSnapshot; } - if (lines[0].trim() !== '' || lines[lines.length - 1].trim() !== '') { + if (lines[0].trim() !== '' || lines.at(-1)!.trim() !== '') { // If not blank first and last lines, abort. return inlineSnapshot; } diff --git a/packages/jest-snapshot/src/utils.ts b/packages/jest-snapshot/src/utils.ts index 13f93fb3adc4..0a185b4e3229 100644 --- a/packages/jest-snapshot/src/utils.ts +++ b/packages/jest-snapshot/src/utils.ts @@ -457,7 +457,7 @@ export const processPrettierAst = ( return; } - const parent = ancestors[ancestors.length - 1].node; + const parent = ancestors.at(-1)!.node; const startColumn = isAwaitExpression(parent) && parent.loc ? parent.loc.start.column diff --git a/packages/jest-test-sequencer/src/__tests__/test_sequencer.test.ts b/packages/jest-test-sequencer/src/__tests__/test_sequencer.test.ts index c060dae3aeef..eb08403491a8 100644 --- a/packages/jest-test-sequencer/src/__tests__/test_sequencer.test.ts +++ b/packages/jest-test-sequencer/src/__tests__/test_sequencer.test.ts @@ -343,10 +343,10 @@ test('return third shard', async () => { }); test('returns expected 100/10 shards', async () => { - const allTests = toTests(new Array(100).fill(true).map((_, i) => `/${i}.js`)); + const allTests = toTests(Array.from({length: 100}).map((_, i) => `/${i}.js`)); const shards = await Promise.all( - new Array(10).fill(true).map((_, i) => + Array.from({length: 10}).map((_, i) => sequencer.shard(allTests, { shardCount: 10, shardIndex: i + 1, @@ -360,10 +360,10 @@ test('returns expected 100/10 shards', async () => { }); test('returns expected 100/8 shards', async () => { - const allTests = toTests(new Array(100).fill(true).map((_, i) => `/${i}.js`)); + const allTests = toTests(Array.from({length: 100}).map((_, i) => `/${i}.js`)); const shards = await Promise.all( - new Array(8).fill(true).map((_, i) => + Array.from({length: 8}).map((_, i) => sequencer.shard(allTests, { shardCount: 8, shardIndex: i + 1, @@ -377,10 +377,10 @@ test('returns expected 100/8 shards', async () => { }); test('returns expected 55/12 shards', async () => { - const allTests = toTests(new Array(55).fill(true).map((_, i) => `/${i}.js`)); + const allTests = toTests(Array.from({length: 55}).map((_, i) => `/${i}.js`)); const shards = await Promise.all( - new Array(12).fill(true).map((_, i) => + Array.from({length: 12}).map((_, i) => sequencer.shard(allTests, { shardCount: 12, shardIndex: i + 1, diff --git a/packages/jest-test-sequencer/src/index.ts b/packages/jest-test-sequencer/src/index.ts index df0f4756bce1..a0604eddc599 100644 --- a/packages/jest-test-sequencer/src/index.ts +++ b/packages/jest-test-sequencer/src/index.ts @@ -91,13 +91,14 @@ export default class TestSequencer { const shardRest = options.suiteLength % options.shardCount; const ratio = options.suiteLength / options.shardCount; - return new Array(options.shardIndex) - .fill(true) - .reduce((acc, _, shardIndex) => { + return Array.from({length: options.shardIndex}).reduce( + (acc, _, shardIndex) => { const dangles = shardIndex < shardRest; const shardSize = dangles ? Math.ceil(ratio) : Math.floor(ratio); return acc + shardSize; - }, 0); + }, + 0, + ); } /** diff --git a/packages/jest-validate/src/validateCLIOptions.ts b/packages/jest-validate/src/validateCLIOptions.ts index 50c47b8dfe3f..405e1f178a25 100644 --- a/packages/jest-validate/src/validateCLIOptions.ts +++ b/packages/jest-validate/src/validateCLIOptions.ts @@ -115,7 +115,6 @@ export default function validateCLIOptions( !allowedOptions.has(camelcase(arg, {locale: 'en-US'})) && !allowedOptions.has(arg) && (rawArgv.length === 0 || rawArgv.includes(arg)), - [], ); if (unrecognizedOptions.length > 0) { diff --git a/packages/jest-worker/src/base/BaseWorkerPool.ts b/packages/jest-worker/src/base/BaseWorkerPool.ts index 3c8ae9be2660..197011039e7e 100644 --- a/packages/jest-worker/src/base/BaseWorkerPool.ts +++ b/packages/jest-worker/src/base/BaseWorkerPool.ts @@ -34,7 +34,7 @@ export default class BaseWorkerPool { constructor(workerPath: string, options: WorkerPoolOptions) { this._options = options; this._workerPath = workerPath; - this._workers = new Array(options.numWorkers); + this._workers = Array.from({length: options.numWorkers}); const stdout = mergeStream(); const stderr = mergeStream(); diff --git a/packages/pretty-format/src/__tests__/prettyFormat.test.ts b/packages/pretty-format/src/__tests__/prettyFormat.test.ts index c27aa71aeb9f..5a245bbc6c79 100644 --- a/packages/pretty-format/src/__tests__/prettyFormat.test.ts +++ b/packages/pretty-format/src/__tests__/prettyFormat.test.ts @@ -577,7 +577,7 @@ describe('prettyFormat()', () => { describe('maxWidth option', () => { it('applies to arrays', () => { - const val = new Array(1_000_000).fill('x'); + const val = Array.from({length: 1_000_000}).fill('x'); expect(prettyFormat(val, {maxWidth: 5})).toEqual( [ 'Array [', diff --git a/packages/pretty-format/src/index.ts b/packages/pretty-format/src/index.ts index a2c19cac3ac8..a99c78f16f98 100644 --- a/packages/pretty-format/src/index.ts +++ b/packages/pretty-format/src/index.ts @@ -504,7 +504,7 @@ const getConfig = (options?: OptionsReceived): Config => ({ }); function createIndent(indent: number): string { - return new Array(indent + 1).join(' '); + return Array.from({length: indent + 1}).join(' '); } /**