diff --git a/.eslintrc.cjs b/.eslintrc.cjs index fe11aae22900..6f195a6f1cd2 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -98,7 +98,6 @@ module.exports = { 'packages/expect/src/index.ts', 'packages/jest-fake-timers/src/legacyFakeTimers.ts', 'packages/jest-jasmine2/src/jestExpect.ts', - 'packages/jest-resolve/src/resolver.ts', ], rules: { 'local/prefer-spread-eventually': 'warn', @@ -332,8 +331,9 @@ module.exports = { ], rules: { '@typescript-eslint/explicit-module-boundary-types': 'off', - 'unicorn/no-await-expression-member': 'off', 'unicorn/consistent-function-scoping': 'off', + 'unicorn/no-await-expression-member': 'off', + 'unicorn/prefer-spread': 'off', }, }, { @@ -676,6 +676,9 @@ module.exports = { // reduce is fine 'unicorn/no-array-reduce': 'off', + // this is very aggressive (600+ files changed). might make sense to apply bit by bit over time? + 'unicorn/prevent-abbreviations': 'off', + // nah 'unicorn/consistent-destructuring': 'off', 'unicorn/no-lonely-if': 'off', @@ -696,9 +699,7 @@ module.exports = { 'unicorn/error-message': 'off', 'unicorn/no-object-as-default-parameter': 'off', 'unicorn/prefer-object-from-entries': 'off', - 'unicorn/prefer-spread': 'off', 'unicorn/prefer-string-replace-all': 'off', - 'unicorn/prevent-abbreviations': 'off', // enabling this is blocked by https://github.com/microsoft/rushstack/issues/2780 'unicorn/prefer-export-from': 'off', diff --git a/docs/Configuration.md b/docs/Configuration.md index 3f282a99921e..26b0ced5a8bd 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -2179,7 +2179,7 @@ class CustomSequencer extends Sequencer { sort(tests) { // Test structure information // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 - const copyTests = Array.from(tests); + const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } } diff --git a/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap b/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap index fe1ba57c9a9b..c8d8b0a2d976 100644 --- a/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap +++ b/e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap @@ -41,7 +41,7 @@ exports[`moduleNameMapper wrong array configuration 1`] = ` 12 | module.exports = () => 'test'; 13 | - at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:1174:17) + at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:1172:17) at Object.require (index.js:10:1) at Object.require (__tests__/index.js:10:20)" `; @@ -71,7 +71,7 @@ exports[`moduleNameMapper wrong configuration 1`] = ` 12 | module.exports = () => 'test'; 13 | - at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:1174:17) + at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:1172:17) at Object.require (index.js:10:1) at Object.require (__tests__/index.js:10:20)" `; diff --git a/e2e/__tests__/__snapshots__/requireMissingExt.test.ts.snap b/e2e/__tests__/__snapshots__/requireMissingExt.test.ts.snap index f7e4f8985ce3..2fbdb214626f 100644 --- a/e2e/__tests__/__snapshots__/requireMissingExt.test.ts.snap +++ b/e2e/__tests__/__snapshots__/requireMissingExt.test.ts.snap @@ -26,7 +26,7 @@ exports[`shows a proper error from deep requires 1`] = ` 12 | test('dummy', () => { 13 | expect(1).toBe(1); - at Resolver._throwModNotFoundError (../../packages/jest-resolve/build/index.js:929:11) + at Resolver._throwModNotFoundError (../../packages/jest-resolve/build/index.js:927:11) at Object. (node_modules/discord.js/src/index.js:21:12) at Object.require (__tests__/test.js:10:1)" `; diff --git a/e2e/__tests__/__snapshots__/resolveNoFileExtensions.test.ts.snap b/e2e/__tests__/__snapshots__/resolveNoFileExtensions.test.ts.snap index a5439509e3da..1372c981269c 100644 --- a/e2e/__tests__/__snapshots__/resolveNoFileExtensions.test.ts.snap +++ b/e2e/__tests__/__snapshots__/resolveNoFileExtensions.test.ts.snap @@ -37,7 +37,7 @@ exports[`show error message with matching files 1`] = ` | ^ 9 | - at Resolver._throwModNotFoundError (../../packages/jest-resolve/build/index.js:929:11) + at Resolver._throwModNotFoundError (../../packages/jest-resolve/build/index.js:927:11) at Object.require (index.js:8:18) at Object.require (__tests__/test.js:8:11)" `; diff --git a/e2e/__tests__/jestChangedFiles.test.ts b/e2e/__tests__/jestChangedFiles.test.ts index a96737a494e1..c3462701a860 100644 --- a/e2e/__tests__/jestChangedFiles.test.ts +++ b/e2e/__tests__/jestChangedFiles.test.ts @@ -85,7 +85,7 @@ testIfHg('gets hg SCM roots and dedupes them', async () => { const repos = await findRepos(roots); expect(repos.git.size).toBe(0); - const hgRepos = Array.from(repos.hg); + const hgRepos = [...repos.hg]; // it's not possible to match the exact path because it will resolve // differently on different platforms. @@ -123,7 +123,7 @@ test('gets git SCM roots and dedupes them', async () => { const repos = await findRepos(roots); expect(repos.hg.size).toBe(0); - const gitRepos = Array.from(repos.git); + const gitRepos = [...repos.git]; // it's not possible to match the exact path because it will resolve // differently on different platforms. @@ -168,9 +168,9 @@ testIfSlAndHg( ].map(filename => path.resolve(DIR, filename)); const repos = await findRepos(roots); - const hgRepos = Array.from(repos.hg); - const gitRepos = Array.from(repos.git); - const slRepos = Array.from(repos.sl); + const hgRepos = [...repos.hg]; + const gitRepos = [...repos.git]; + const slRepos = [...repos.sl]; // NOTE: This test can break if you have a .git or .hg repo initialized // inside your os tmp directory. @@ -207,11 +207,11 @@ test('gets changed files for git', async () => { ].map(filename => path.resolve(DIR, filename)); let {changedFiles: files} = await getChangedFilesForRoots(roots, {}); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file2.txt', 'file3.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file2.txt', + 'file3.txt', + ]); run(`${GIT} add .`, DIR); @@ -223,37 +223,33 @@ test('gets changed files for git', async () => { gitCreateBranch('nested-dir', DIR); ({changedFiles: files} = await getChangedFilesForRoots(roots, {})); - expect(Array.from(files)).toEqual([]); + expect([...files]).toEqual([]); ({changedFiles: files} = await getChangedFilesForRoots(roots, { lastCommit: true, })); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file2.txt', 'file3.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file2.txt', + 'file3.txt', + ]); writeFiles(DIR, { 'file1.txt': 'modified file1', }); ({changedFiles: files} = await getChangedFilesForRoots(roots, {})); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + ]); run(`${GIT} add -A`, DIR); // staged files should be included ({changedFiles: files} = await getChangedFilesForRoots(roots, {})); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + ]); run(`${GIT} commit --no-gpg-sign -am "test2"`, DIR); @@ -265,11 +261,10 @@ test('gets changed files for git', async () => { withAncestor: true, })); // Returns files from current uncommitted state + the last commit - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file4.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file4.txt', + ]); run(`${GIT} add file4.txt`, DIR); run(`${GIT} commit --no-gpg-sign -m "test3"`, DIR); @@ -278,11 +273,10 @@ test('gets changed files for git', async () => { changedSince: 'HEAD^^', })); // Returns files from the last 2 commits - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file4.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file4.txt', + ]); run(`${GIT} checkout HEAD^^ -b feature-branch`, DIR); @@ -296,11 +290,9 @@ test('gets changed files for git', async () => { changedSince: mainBranchName, })); // Returns files from this branch but not ones that only exist on mainBranchName - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file5.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file5.txt', + ]); }); test('monitors only root paths for git', async () => { @@ -315,11 +307,10 @@ test('monitors only root paths for git', async () => { const roots = [path.resolve(DIR, 'nested-dir')]; const {changedFiles: files} = await getChangedFilesForRoots(roots, {}); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file2.txt', 'file3.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file2.txt', + 'file3.txt', + ]); }); it('does not find changes in files with no diff, for git', async () => { @@ -351,7 +342,7 @@ it('does not find changes in files with no diff, for git', async () => { // check that passing in no changedSince arg doesn't return any unstaged / other changes const {changedFiles: files} = await getChangedFilesForRoots(roots, {}); - expect(Array.from(files)).toEqual([]); + expect([...files]).toEqual([]); // check that in diff from `jestChangedFilesSpecBase` branch, no changed files are reported const {changedFiles: filesExplicitBaseBranch} = await getChangedFilesForRoots( @@ -360,7 +351,7 @@ it('does not find changes in files with no diff, for git', async () => { changedSince: 'jestChangedFilesSpecBase', }, ); - expect(Array.from(filesExplicitBaseBranch)).toEqual([]); + expect([...filesExplicitBaseBranch]).toEqual([]); }); test('handles a bad revision for "changedSince", for git', async () => { @@ -400,37 +391,35 @@ testIfHg('gets changed files for hg', async () => { ); let {changedFiles: files} = await getChangedFilesForRoots(roots, {}); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file2.txt', 'file3.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file2.txt', + 'file3.txt', + ]); run(`${HG} add .`, DIR); run(`${HG} commit -l file1.txt`, DIR); ({changedFiles: files} = await getChangedFilesForRoots(roots, {})); - expect(Array.from(files)).toEqual([]); + expect([...files]).toEqual([]); ({changedFiles: files} = await getChangedFilesForRoots(roots, { lastCommit: true, })); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file2.txt', 'file3.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file2.txt', + 'file3.txt', + ]); writeFiles(DIR, { 'file1.txt': 'modified file1', }); ({changedFiles: files} = await getChangedFilesForRoots(roots, {})); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + ]); run(`${HG} commit -m "test2"`, DIR); @@ -442,11 +431,10 @@ testIfHg('gets changed files for hg', async () => { withAncestor: true, })); // Returns files from current uncommitted state + the last commit - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file4.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file4.txt', + ]); run(`${HG} add file4.txt`, DIR); run(`${HG} commit -m "test3"`, DIR); @@ -455,11 +443,10 @@ testIfHg('gets changed files for hg', async () => { changedSince: '-3', })); // Returns files from the last 2 commits - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file4.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file4.txt', + ]); run(`${HG} bookmark main`, DIR); // Back up and develop on a different branch @@ -475,11 +462,9 @@ testIfHg('gets changed files for hg', async () => { changedSince: 'main', })); // Returns files from this branch but not ones that only exist on main - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file5.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file5.txt', + ]); }); testIfHg('monitors only root paths for hg', async () => { @@ -494,11 +479,10 @@ testIfHg('monitors only root paths for hg', async () => { const roots = [path.resolve(DIR, 'nested-dir')]; const {changedFiles: files} = await getChangedFilesForRoots(roots, {}); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file2.txt', 'file3.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file2.txt', + 'file3.txt', + ]); }); testIfHg('handles a bad revision for "changedSince", for hg', async () => { @@ -546,7 +530,7 @@ testIfSl('gets sl SCM roots and dedupes them', async () => { expect(repos.git.size).toBe(0); expect(repos.hg.size).toBe(0); - const slRepos = Array.from(repos.sl); + const slRepos = [...repos.sl]; // it's not possible to match the exact path because it will resolve // differently on different platforms. @@ -579,37 +563,35 @@ testIfSl('gets changed files for sl', async () => { ); let {changedFiles: files} = await getChangedFilesForRoots(roots, {}); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file2.txt', 'file3.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file2.txt', + 'file3.txt', + ]); run(`${SL} add .`, DIR); run(`${SL} commit -l file1.txt`, DIR); ({changedFiles: files} = await getChangedFilesForRoots(roots, {})); - expect(Array.from(files)).toEqual([]); + expect([...files]).toEqual([]); ({changedFiles: files} = await getChangedFilesForRoots(roots, { lastCommit: true, })); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file2.txt', 'file3.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file2.txt', + 'file3.txt', + ]); writeFiles(DIR, { 'file1.txt': 'modified file1', }); ({changedFiles: files} = await getChangedFilesForRoots(roots, {})); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + ]); run(`${SL} commit -m "test2"`, DIR); @@ -621,11 +603,10 @@ testIfSl('gets changed files for sl', async () => { withAncestor: true, })); // Returns files from current uncommitted state + the last commit - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file4.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file4.txt', + ]); run(`${SL} add file4.txt`, DIR); run(`${SL} commit -m "test3"`, DIR); @@ -634,11 +615,10 @@ testIfSl('gets changed files for sl', async () => { changedSince: '.~2', })); // Returns files from the last 2 commits - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file1.txt', 'file4.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file1.txt', + 'file4.txt', + ]); run(`${SL} bookmark main_branch`, DIR); // Back up and develop on a different branch @@ -655,11 +635,9 @@ testIfSl('gets changed files for sl', async () => { changedSince: 'main_branch', })); // Returns files from this branch but not ones that only exist on main - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file5.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file5.txt', + ]); }); testIfSl('monitors only root paths for sl', async () => { @@ -674,11 +652,10 @@ testIfSl('monitors only root paths for sl', async () => { const roots = [path.resolve(DIR, 'nested-dir')]; const {changedFiles: files} = await getChangedFilesForRoots(roots, {}); - expect( - Array.from(files) - .map(filePath => path.basename(filePath)) - .sort(), - ).toEqual(['file2.txt', 'file3.txt']); + expect([...files].map(filePath => path.basename(filePath)).sort()).toEqual([ + 'file2.txt', + 'file3.txt', + ]); }); testIfSl('handles a bad revision for "changedSince", for sl', async () => { diff --git a/e2e/custom-esm-test-sequencer/testSequencer.mjs b/e2e/custom-esm-test-sequencer/testSequencer.mjs index 21e4a9ef3459..5e9fcb2cfba2 100644 --- a/e2e/custom-esm-test-sequencer/testSequencer.mjs +++ b/e2e/custom-esm-test-sequencer/testSequencer.mjs @@ -9,7 +9,7 @@ import Sequencer from '@jest/test-sequencer'; export default class CustomSequencer extends Sequencer { sort(tests) { - const copyTests = Array.from(tests); + const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } } diff --git a/e2e/custom-test-sequencer/testSequencer.js b/e2e/custom-test-sequencer/testSequencer.js index 2c60884b64ad..30c2f11b8d01 100644 --- a/e2e/custom-test-sequencer/testSequencer.js +++ b/e2e/custom-test-sequencer/testSequencer.js @@ -9,7 +9,7 @@ const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { sort(tests) { - const copyTests = Array.from(tests); + const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } } diff --git a/e2e/custom-test-sequencer/testSequencerAsync.js b/e2e/custom-test-sequencer/testSequencerAsync.js index d635461ca576..046e4ee3dbe7 100644 --- a/e2e/custom-test-sequencer/testSequencerAsync.js +++ b/e2e/custom-test-sequencer/testSequencerAsync.js @@ -12,7 +12,7 @@ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); class CustomSequencer extends Sequencer { async sort(tests) { await sleep(50); - const copyTests = Array.from(tests); + const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } diff --git a/e2e/custom-test-sequencer/testSequencerWithSeed.js b/e2e/custom-test-sequencer/testSequencerWithSeed.js index 1ed6db6cffeb..925120e82e1f 100644 --- a/e2e/custom-test-sequencer/testSequencerWithSeed.js +++ b/e2e/custom-test-sequencer/testSequencerWithSeed.js @@ -14,7 +14,7 @@ class CustomSequencer extends Sequencer { } sort(tests) { - const copyTests = Array.from(tests); + const copyTests = [...tests]; const seed = this.globalConfig.seed; const sortedTests = copyTests.sort((testA, testB) => testA.path > testB.path ? 1 : -1, diff --git a/e2e/expect-async-matcher/babel.config.js b/e2e/expect-async-matcher/babel.config.js index d093998fcf92..18d350351f3e 100644 --- a/e2e/expect-async-matcher/babel.config.js +++ b/e2e/expect-async-matcher/babel.config.js @@ -8,5 +8,5 @@ const baseConfig = require('../../babel.config'); module.exports = Object.assign({}, baseConfig, { - presets: baseConfig.presets.concat('@babel/preset-flow'), + presets: [...baseConfig.presets, '@babel/preset-flow'], }); diff --git a/e2e/failures/babel.config.js b/e2e/failures/babel.config.js index d093998fcf92..18d350351f3e 100644 --- a/e2e/failures/babel.config.js +++ b/e2e/failures/babel.config.js @@ -8,5 +8,5 @@ const baseConfig = require('../../babel.config'); module.exports = Object.assign({}, baseConfig, { - presets: baseConfig.presets.concat('@babel/preset-flow'), + presets: [...baseConfig.presets, '@babel/preset-flow'], }); diff --git a/e2e/runJest.ts b/e2e/runJest.ts index 3a2bc5d756ae..73eeb9056ede 100644 --- a/e2e/runJest.ts +++ b/e2e/runJest.ts @@ -273,7 +273,7 @@ export function getConfig( } { const {exitCode, stdout, stderr} = runJest( dir, - args.concat('--show-config'), + [...args, '--show-config'], options, ); diff --git a/e2e/shard/sharding-test-sequencer.js b/e2e/shard/sharding-test-sequencer.js index 257f959d0469..0aa8f8b57077 100644 --- a/e2e/shard/sharding-test-sequencer.js +++ b/e2e/shard/sharding-test-sequencer.js @@ -7,7 +7,7 @@ module.exports = class NoShardingSequencer { shard(tests) { return [ - Array.from(tests).sort((a, b) => + [...tests].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0, )[2], ]; diff --git a/e2e/worker-restart-before-send/testSequencer.js b/e2e/worker-restart-before-send/testSequencer.js index a5e9b5d43ed5..3c00126fd1f0 100644 --- a/e2e/worker-restart-before-send/testSequencer.js +++ b/e2e/worker-restart-before-send/testSequencer.js @@ -14,7 +14,7 @@ class CustomSequencer extends Sequencer { sort(tests) { // Test structure information // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 - const copyTests = Array.from(tests); + const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } } diff --git a/packages/babel-jest/src/index.ts b/packages/babel-jest/src/index.ts index cb11e6cfe9fa..300e8b3c8b21 100644 --- a/packages/babel-jest/src/index.ts +++ b/packages/babel-jest/src/index.ts @@ -51,7 +51,8 @@ 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 ?? []), [ babelIstanbulPlugin, { @@ -60,7 +61,7 @@ function addIstanbulInstrumentation( exclude: [], }, ], - ]); + ]; return copiedBabelOptions; } @@ -166,9 +167,9 @@ export const createTransformer: TransformerCreator< }, compact: false, plugins: inputOptions.plugins ?? [], - presets: (inputOptions.presets ?? []).concat(jestPresetPath), + presets: [...(inputOptions.presets ?? []), jestPresetPath], sourceMaps: 'both', - } as const; + } satisfies TransformOptions; function mergeBabelTransformOptions( filename: string, diff --git a/packages/babel-plugin-jest-hoist/src/index.ts b/packages/babel-plugin-jest-hoist/src/index.ts index fa440163ea03..381fdad2560e 100644 --- a/packages/babel-plugin-jest-hoist/src/index.ts +++ b/packages/babel-plugin-jest-hoist/src/index.ts @@ -191,9 +191,7 @@ FUNCTIONS.mock = args => { 'The module factory of `jest.mock()` is not allowed to ' + 'reference any out-of-scope variables.\n' + `Invalid variable access: ${name}\n` + - `Allowed objects: ${Array.from(ALLOWED_IDENTIFIERS).join( - ', ', - )}.\n` + + `Allowed objects: ${[...ALLOWED_IDENTIFIERS].join(', ')}.\n` + 'Note: This is a precaution to guard against uninitialized mock ' + 'variables. If it is ensured that the mock is required lazily, ' + 'variable names prefixed with `mock` (case insensitive) are permitted.\n', diff --git a/packages/create-jest/src/runCreate.ts b/packages/create-jest/src/runCreate.ts index 7776f484d378..fcaa3d46a3f1 100644 --- a/packages/create-jest/src/runCreate.ts +++ b/packages/create-jest/src/runCreate.ts @@ -56,7 +56,7 @@ export async function runCreate(rootDir = process.cwd()): Promise { throw new NotFoundPackageJsonError(rootDir); } - const questions = defaultQuestions.slice(0); + const questions = [...defaultQuestions]; let hasJestProperty = false; let projectPackageJson: ProjectPackageJson; diff --git a/packages/expect-utils/src/jasmineUtils.ts b/packages/expect-utils/src/jasmineUtils.ts index e5f32eed4dd9..b19f0217fe41 100644 --- a/packages/expect-utils/src/jasmineUtils.ts +++ b/packages/expect-utils/src/jasmineUtils.ts @@ -213,14 +213,15 @@ function keys(obj: object, hasKey: (obj: object, key: string) => boolean) { keys.push(key); } } - return keys.concat( - (Object.getOwnPropertySymbols(obj) as Array).filter( + return [ + ...keys, + ...Object.getOwnPropertySymbols(obj).filter( symbol => Object.getOwnPropertyDescriptor(obj, symbol)!.enumerable, ), - ); + ]; } -function hasKey(obj: any, key: string) { +function hasKey(obj: any, key: string | symbol) { return Object.prototype.hasOwnProperty.call(obj, key); } diff --git a/packages/expect-utils/src/utils.ts b/packages/expect-utils/src/utils.ts index dc4250fe5bbc..6fb9395f987c 100644 --- a/packages/expect-utils/src/utils.ts +++ b/packages/expect-utils/src/utils.ts @@ -323,10 +323,11 @@ export const iterableEquality = ( const entries = (obj: any) => { if (!isObject(obj)) return []; - return Object.getOwnPropertySymbols(obj) + const symbolProperties = Object.getOwnPropertySymbols(obj) .filter(key => key !== Symbol.iterator) - .map(key => [key, obj[key]]) - .concat(Object.entries(obj)); + .map(key => [key, obj[key]]); + + return [...symbolProperties, ...Object.entries(obj)]; }; const isObject = (a: any) => a !== null && typeof a === 'object'; diff --git a/packages/expect/src/matchers.ts b/packages/expect/src/matchers.ts index 970d8dd1a291..a7e9e6df639e 100644 --- a/packages/expect/src/matchers.ts +++ b/packages/expect/src/matchers.ts @@ -535,7 +535,7 @@ const matchers: MatchersObject = { return {message, pass}; } - const indexable = Array.from(received); + const indexable = [...received]; const index = indexable.indexOf(expected); const pass = index !== -1; @@ -587,7 +587,7 @@ const matchers: MatchersObject = { ); } - const index = Array.from(received).findIndex(item => + const index = [...received].findIndex(item => equals(item, expected, [...this.customTesters, iterableEquality]), ); const pass = index !== -1; diff --git a/packages/jest-changed-files/src/git.ts b/packages/jest-changed-files/src/git.ts index c1d8a01d04cf..6695d9a885ce 100644 --- a/packages/jest-changed-files/src/git.ts +++ b/packages/jest-changed-files/src/git.ts @@ -46,22 +46,31 @@ const adapter: SCMAdapter = { if (options.lastCommit === true) { return findChangedFilesUsingCommand( - ['show', '--name-only', '--pretty=format:', 'HEAD', '--'].concat( - includePaths, - ), + [ + 'show', + '--name-only', + '--pretty=format:', + 'HEAD', + '--', + ...includePaths, + ], cwd, ); } if (changedSince != null && changedSince.length > 0) { const [committed, staged, unstaged] = await Promise.all([ findChangedFilesUsingCommand( - ['diff', '--name-only', `${changedSince}...HEAD`, '--'].concat( - includePaths, - ), + [ + 'diff', + '--name-only', + `${changedSince}...HEAD`, + '--', + ...includePaths, + ], cwd, ), findChangedFilesUsingCommand( - ['diff', '--cached', '--name-only', '--'].concat(includePaths), + ['diff', '--cached', '--name-only', '--', ...includePaths], cwd, ), findChangedFilesUsingCommand( @@ -71,7 +80,8 @@ const adapter: SCMAdapter = { '--modified', '--exclude-standard', '--', - ].concat(includePaths), + ...includePaths, + ], cwd, ), ]); @@ -79,7 +89,7 @@ const adapter: SCMAdapter = { } const [staged, unstaged] = await Promise.all([ findChangedFilesUsingCommand( - ['diff', '--cached', '--name-only', '--'].concat(includePaths), + ['diff', '--cached', '--name-only', '--', ...includePaths], cwd, ), findChangedFilesUsingCommand( @@ -89,7 +99,8 @@ const adapter: SCMAdapter = { '--modified', '--exclude-standard', '--', - ].concat(includePaths), + ...includePaths, + ], cwd, ), ]); diff --git a/packages/jest-circus/src/globalErrorHandlers.ts b/packages/jest-circus/src/globalErrorHandlers.ts index d7cfba857a26..157300113cc3 100644 --- a/packages/jest-circus/src/globalErrorHandlers.ts +++ b/packages/jest-circus/src/globalErrorHandlers.ts @@ -31,9 +31,9 @@ const rejectionHandledListener: NodeJS.RejectionHandledListener = ( export const injectGlobalErrorHandlers = ( parentProcess: typeof Process, ): Circus.GlobalErrorHandlers => { - const uncaughtException = process.listeners('uncaughtException').slice(); - const unhandledRejection = process.listeners('unhandledRejection').slice(); - const rejectionHandled = process.listeners('rejectionHandled').slice(); + const uncaughtException = [...process.listeners('uncaughtException')]; + const unhandledRejection = [...process.listeners('unhandledRejection')]; + const rejectionHandled = [...process.listeners('rejectionHandled')]; parentProcess.removeAllListeners('uncaughtException'); parentProcess.removeAllListeners('unhandledRejection'); parentProcess.removeAllListeners('rejectionHandled'); diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts index 2a16a8635a66..eeea251f4774 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts @@ -145,7 +145,7 @@ const _addSnapshotData = ( results.snapshot.updated = snapshotState.updated; results.snapshot.unchecked = status.deleted ? 0 : uncheckedCount; // Copy the array to prevent memory leaks - results.snapshot.uncheckedKeys = Array.from(uncheckedKeys); + results.snapshot.uncheckedKeys = [...uncheckedKeys]; }; export default jestAdapter; 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 a26db7e15494..5c71ce1aafa4 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts @@ -112,7 +112,7 @@ export const initialize = async ({ // Jest tests snapshotSerializers in order preceding built-in serializers. // Therefore, add in reverse because the last added is the first tested. - for (const path of config.snapshotSerializers.concat().reverse()) + for (const path of [...config.snapshotSerializers].reverse()) addSerializer(localRequire(path)); const snapshotResolver = await buildSnapshotResolver(config, localRequire); @@ -190,7 +190,7 @@ export const runAndTransformResultsToJestFormat = async ({ failureDetails: testResult.errorsDetailed, failureMessages: testResult.errors, fullName: title - ? ancestorTitles.concat(title).join(' ') + ? [...ancestorTitles, title].join(' ') : ancestorTitles.join(' '), invocations: testResult.invocations, location: testResult.location, @@ -275,7 +275,7 @@ const eventHandler = async (event: Circus.Event) => { const _addExpectedAssertionErrors = (test: Circus.TestEntry) => { const failures = jestExpect.extractExpectedAssertionsErrors(); const errors = failures.map(failure => failure.error); - test.errors = test.errors.concat(errors); + test.errors = [...test.errors, ...errors]; }; // Get suppressed errors from ``jest-matchers`` that weren't throw during @@ -285,6 +285,6 @@ const _addSuppressedErrors = (test: Circus.TestEntry) => { const {suppressedErrors} = jestExpect.getState(); jestExpect.setState({suppressedErrors: []}); if (suppressedErrors.length > 0) { - test.errors = test.errors.concat(suppressedErrors); + test.errors = [...test.errors, ...suppressedErrors]; } }; diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts index eefd51feac4e..4354a7aed31a 100644 --- a/packages/jest-circus/src/utils.ts +++ b/packages/jest-circus/src/utils.ts @@ -384,7 +384,7 @@ export const makeSingleTestResult = ( retryReasons: test.retryReasons.map(_getError).map(getErrorStack), startedAt: test.startedAt, status, - testPath: Array.from(testPath), + testPath: [...testPath], }; }; @@ -510,12 +510,12 @@ export const parseSingleTestResult = ( duration: testResult.duration, failing: testResult.failing, failureDetails: testResult.errorsDetailed, - failureMessages: Array.from(testResult.errors), + failureMessages: [...testResult.errors], fullName, invocations: testResult.invocations, location: testResult.location, numPassingAsserts: testResult.numPassingAsserts, - retryReasons: Array.from(testResult.retryReasons), + retryReasons: [...testResult.retryReasons], status, title, }; diff --git a/packages/jest-config/src/__tests__/resolveConfigPath.test.ts b/packages/jest-config/src/__tests__/resolveConfigPath.test.ts index cd4667473bbb..12c0c0cec961 100644 --- a/packages/jest-config/src/__tests__/resolveConfigPath.test.ts +++ b/packages/jest-config/src/__tests__/resolveConfigPath.test.ts @@ -19,7 +19,7 @@ const MULTIPLE_CONFIGS_ERROR_PATTERN = /Multiple configurations found/; beforeEach(() => cleanup(DIR)); afterEach(() => cleanup(DIR)); -describe.each(JEST_CONFIG_EXT_ORDER.slice(0))( +describe.each([...JEST_CONFIG_EXT_ORDER])( 'Resolve config path %s', extension => { test(`file path with "${extension}"`, () => { diff --git a/packages/jest-config/src/normalize.ts b/packages/jest-config/src/normalize.ts index 9062f3dfd600..4d2ebcad3282 100644 --- a/packages/jest-config/src/normalize.ts +++ b/packages/jest-config/src/normalize.ts @@ -187,17 +187,19 @@ const setupPreset = async ( } if (options.setupFiles) { - options.setupFiles = (preset.setupFiles || []).concat(options.setupFiles); + options.setupFiles = [...(preset.setupFiles || []), ...options.setupFiles]; } if (options.setupFilesAfterEnv) { - options.setupFilesAfterEnv = (preset.setupFilesAfterEnv || []).concat( - options.setupFilesAfterEnv, - ); + options.setupFilesAfterEnv = [ + ...(preset.setupFilesAfterEnv || []), + ...options.setupFilesAfterEnv, + ]; } if (options.modulePathIgnorePatterns && preset.modulePathIgnorePatterns) { - options.modulePathIgnorePatterns = preset.modulePathIgnorePatterns.concat( - options.modulePathIgnorePatterns, - ); + options.modulePathIgnorePatterns = [ + ...preset.modulePathIgnorePatterns, + ...options.modulePathIgnorePatterns, + ]; } mergeOptionWithPreset(options, preset, 'moduleNameMapper'); mergeOptionWithPreset(options, preset, 'transform'); @@ -758,9 +760,14 @@ export default async function normalize( typeof project === 'string' ? glob.sync(project, {windowsPathsNoEscape: true}) : []; - return projects.concat( - globMatches.length > 0 ? globMatches : project, - ); + const projectEntry = + globMatches.length > 0 ? globMatches : project; + return [ + ...projects, + ...(Array.isArray(projectEntry) + ? projectEntry + : [projectEntry]), + ]; }, [], ); diff --git a/packages/jest-core/src/ReporterDispatcher.ts b/packages/jest-core/src/ReporterDispatcher.ts index b019682548b5..451bb5bd6102 100644 --- a/packages/jest-core/src/ReporterDispatcher.ts +++ b/packages/jest-core/src/ReporterDispatcher.ts @@ -106,8 +106,8 @@ export default class ReporterDispatcher { // Return a list of last errors for every reporter getErrors(): Array { return this._reporters.reduce>((list, reporter) => { - const error = reporter.getLastError && reporter.getLastError(); - return error ? list.concat(error) : list; + const error = reporter.getLastError?.(); + return error ? [...list, error] : list; }, []); } diff --git a/packages/jest-core/src/SearchSource.ts b/packages/jest-core/src/SearchSource.ts index 16fd46a7a9c4..4ea2c9d59a97 100644 --- a/packages/jest-core/src/SearchSource.ts +++ b/packages/jest-core/src/SearchSource.ts @@ -131,7 +131,7 @@ export default class SearchSource { total: allPaths.length, }; - const testCases = Array.from(this._testPathCases); // clone + const testCases = [...this._testPathCases]; // clone if (testPathPatterns.isSet()) { testCases.push({ isMatch: (path: string) => testPathPatterns.isMatch(path), @@ -195,9 +195,7 @@ export default class SearchSource { {skipNodeResolution: this._context.config.skipNodeResolution}, ); - const allPathsAbsolute = new Set( - Array.from(allPaths).map(p => path.resolve(p)), - ); + const allPathsAbsolute = new Set([...allPaths].map(p => path.resolve(p))); const collectCoverageFrom = new Set(); @@ -369,6 +367,6 @@ export default class SearchSource { for (const sourcePath of sourcePaths) relatedSourcesSet.add(sourcePath); } } - return Array.from(relatedSourcesSet); + return [...relatedSourcesSet]; } } diff --git a/packages/jest-core/src/TestScheduler.ts b/packages/jest-core/src/TestScheduler.ts index ec56b9479098..090b650f55a7 100644 --- a/packages/jest-core/src/TestScheduler.ts +++ b/packages/jest-core/src/TestScheduler.ts @@ -174,7 +174,7 @@ class TestScheduler { const updateSnapshotState = async () => { const contextsWithSnapshotResolvers = await Promise.all( - Array.from(testContexts).map( + [...testContexts].map( async context => [context, await buildSnapshotResolver(context.config)] as const, ), @@ -189,9 +189,10 @@ class TestScheduler { ); aggregatedResults.snapshot.filesRemoved += status.filesRemoved; - aggregatedResults.snapshot.filesRemovedList = ( - aggregatedResults.snapshot.filesRemovedList || [] - ).concat(status.filesRemovedList); + aggregatedResults.snapshot.filesRemovedList = [ + ...(aggregatedResults.snapshot.filesRemovedList || []), + ...status.filesRemovedList, + ]; } const updateAll = this._globalConfig.updateSnapshot === 'all'; aggregatedResults.snapshot.didUpdate = updateAll; @@ -213,7 +214,7 @@ class TestScheduler { try { await Promise.all( - Array.from(testContexts).map(async context => { + [...testContexts].map(async context => { const {config} = context; if (!testRunners[config.runner]) { const transformer = await createScriptTransformer(config); diff --git a/packages/jest-core/src/__tests__/SearchSource.test.ts b/packages/jest-core/src/__tests__/SearchSource.test.ts index 1ec593bbf37d..e7fecf9bdc96 100644 --- a/packages/jest-core/src/__tests__/SearchSource.test.ts +++ b/packages/jest-core/src/__tests__/SearchSource.test.ts @@ -452,7 +452,7 @@ describe('SearchSource', () => { new Set([regular, requireRegular, unrelatedFile]), true, ); - expect(Array.from(data.collectCoverageFrom || [])).toEqual([ + expect([...(data.collectCoverageFrom || [])]).toEqual([ 'RegularModule.js', ]); }); diff --git a/packages/jest-core/src/__tests__/watch.test.js b/packages/jest-core/src/__tests__/watch.test.js index 8dc175f789c3..afef7be7cbb4 100644 --- a/packages/jest-core/src/__tests__/watch.test.js +++ b/packages/jest-core/src/__tests__/watch.test.js @@ -45,7 +45,7 @@ jest.doMock( '../runJest', () => function () { - const args = Array.from(arguments); + const args = [...arguments]; const [{onComplete}] = args; runJestMock.apply(null, args); diff --git a/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js b/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js index 89e70617d494..05c51cd14c64 100644 --- a/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js +++ b/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js @@ -55,7 +55,7 @@ jest.doMock( '../runJest', () => function () { - const args = Array.from(arguments); + const args = [...arguments]; const [{onComplete}] = args; runJestMock.apply(null, args); diff --git a/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js b/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js index 0763d17bf0a0..0be6674c2cd7 100644 --- a/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js +++ b/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js @@ -31,7 +31,7 @@ jest.doMock( '../runJest', () => function () { - const args = Array.from(arguments); + const args = [...arguments]; const [{onComplete}] = args; runJestMock.apply(null, args); diff --git a/packages/jest-core/src/collectHandles.ts b/packages/jest-core/src/collectHandles.ts index 2f16c999f54c..17a6a30fa0ed 100644 --- a/packages/jest-core/src/collectHandles.ts +++ b/packages/jest-core/src/collectHandles.ts @@ -147,7 +147,7 @@ export default function collectHandles(): HandleCollectionResult { hook.disable(); // Get errors for every async resource still referenced at this moment - const result = Array.from(activeHandles.values()) + const result = [...activeHandles.values()] .filter(({isActive}) => isActive()) .map(({error}) => error); @@ -197,7 +197,7 @@ export function formatHandleErrors( stacks.set(stackText, stack); } - return Array.from(stacks.values()).map(({stack, names}) => - stack.replace('%%OBJECT_NAME%%', Array.from(names).join(',')), + return [...stacks.values()].map(({stack, names}) => + stack.replace('%%OBJECT_NAME%%', [...names].join(',')), ); } diff --git a/packages/jest-core/src/runJest.ts b/packages/jest-core/src/runJest.ts index 189ecf18450a..565cec8fc7f2 100644 --- a/packages/jest-core/src/runJest.ts +++ b/packages/jest-core/src/runJest.ts @@ -194,7 +194,7 @@ export default async function runJest({ jestHooks, filter, ); - allTests = allTests.concat(matches.tests); + allTests = [...allTests, ...matches.tests]; return {context, matches}; }), @@ -213,7 +213,7 @@ export default async function runJest({ allTests = await sequencer.sort(allTests); if (globalConfig.listTests) { - const testsPaths = Array.from(new Set(allTests.map(test => test.path))); + const testsPaths = [...new Set(allTests.map(test => test.path))]; /* eslint-disable no-console */ if (globalConfig.json) { console.log(JSON.stringify(testsPaths)); diff --git a/packages/jest-core/src/watch.ts b/packages/jest-core/src/watch.ts index 21cf3d2661a9..42f798f6fab2 100644 --- a/packages/jest-core/src/watch.ts +++ b/packages/jest-core/src/watch.ts @@ -257,7 +257,7 @@ export default async function watch( activePlugin = null; - searchSources = searchSources.slice(); + searchSources = [...searchSources]; searchSources[index] = { context, searchSource: new SearchSource(context), @@ -365,7 +365,7 @@ export default async function watch( if ( isRunning && testWatcher && - ['q', KEYS.ENTER, 'a', 'o', 'f'].concat(pluginKeys).includes(key) + ['q', KEYS.ENTER, 'a', 'o', 'f', ...pluginKeys].includes(key) ) { testWatcher.setState({interrupted: true}); return; diff --git a/packages/jest-diff/src/index.ts b/packages/jest-diff/src/index.ts index 32581c98326d..7c16364bcaae 100644 --- a/packages/jest-diff/src/index.ts +++ b/packages/jest-diff/src/index.ts @@ -122,11 +122,11 @@ function comparePrimitive( } function sortMap(map: Map) { - return new Map(Array.from(map.entries()).sort()); + return new Map([...map.entries()].sort()); } function sortSet(set: Set) { - return new Set(Array.from(set.values()).sort()); + return new Set([...set.values()].sort()); } function compareObjects( diff --git a/packages/jest-docblock/src/index.ts b/packages/jest-docblock/src/index.ts index ff9f94d08033..bbf4fad3b132 100644 --- a/packages/jest-docblock/src/index.ts +++ b/packages/jest-docblock/src/index.ts @@ -69,7 +69,12 @@ export function parseWithComments(docblock: string): { typeof result[match[1]] === 'string' || Array.isArray(result[match[1]]) ) { - result[match[1]] = STRING_ARRAY.concat(result[match[1]], nextPragma); + const resultElement = result[match[1]]; + result[match[1]] = [ + ...STRING_ARRAY, + ...(Array.isArray(resultElement) ? resultElement : [resultElement]), + nextPragma, + ]; } else { result[match[1]] = nextPragma; } @@ -123,7 +128,8 @@ export function print({ } function printKeyValues(key: string, valueOrArray: string | Array) { - return STRING_ARRAY.concat(valueOrArray).map(value => - `@${key} ${value}`.trim(), - ); + return [ + ...STRING_ARRAY, + ...(Array.isArray(valueOrArray) ? valueOrArray : [valueOrArray]), + ].map(value => `@${key} ${value}`.trim()); } diff --git a/packages/jest-fake-timers/src/legacyFakeTimers.ts b/packages/jest-fake-timers/src/legacyFakeTimers.ts index f955ae35161c..455a7cd446b4 100644 --- a/packages/jest-fake-timers/src/legacyFakeTimers.ts +++ b/packages/jest-fake-timers/src/legacyFakeTimers.ts @@ -245,7 +245,7 @@ export default class FakeTimers { // We need to hold the current shape of `this._timers` because existing // timers can add new ones to the map and hence would run more than necessary. // See https://github.com/jestjs/jest/pull/4608 for details - const timerEntries = Array.from(this._timers.entries()); + const timerEntries = [...this._timers.entries()]; this._checkFakeTimers(); for (const _immediate of this._immediates) this._runImmediate(_immediate); @@ -261,7 +261,7 @@ export default class FakeTimers { if (steps < 1) { return; } - const nextExpiry = Array.from(this._timers.values()).reduce( + const nextExpiry = [...this._timers.values()].reduce( (minExpiry: number | null, timer: Timer): number => { if (minExpiry === null || timer.expiry < minExpiry) return timer.expiry; return minExpiry; diff --git a/packages/jest-fake-timers/src/modernFakeTimers.ts b/packages/jest-fake-timers/src/modernFakeTimers.ts index e8b7056fc46a..1ba8b8f931d7 100644 --- a/packages/jest-fake-timers/src/modernFakeTimers.ts +++ b/packages/jest-fake-timers/src/modernFakeTimers.ts @@ -220,7 +220,7 @@ export default class FakeTimers { now: fakeTimersConfig.now ?? Date.now(), shouldAdvanceTime: Boolean(fakeTimersConfig.advanceTimers), shouldClearNativeTimers: true, - toFake: Array.from(toFake), + toFake: [...toFake], }; } } diff --git a/packages/jest-haste-map/src/HasteFS.ts b/packages/jest-haste-map/src/HasteFS.ts index c8b01dac68a1..dc2010bc92dd 100644 --- a/packages/jest-haste-map/src/HasteFS.ts +++ b/packages/jest-haste-map/src/HasteFS.ts @@ -51,7 +51,7 @@ export default class HasteFS implements IHasteFS { } getAllFiles(): Array { - return Array.from(this.getAbsoluteFileIterator()); + return [...this.getAbsoluteFileIterator()]; } getFileIterator(): Iterable { diff --git a/packages/jest-haste-map/src/ModuleMap.ts b/packages/jest-haste-map/src/ModuleMap.ts index 94e355901278..39119bcc29b5 100644 --- a/packages/jest-haste-map/src/ModuleMap.ts +++ b/packages/jest-haste-map/src/ModuleMap.ts @@ -27,7 +27,7 @@ export default class ModuleMap implements IModuleMap { private static mapToArrayRecursive( map: Map, ): Array<[string, unknown]> { - let arr = Array.from(map); + let arr = [...map]; if (arr[0] && arr[0][1] instanceof Map) { arr = arr.map( el => [el[0], this.mapToArrayRecursive(el[1])] as [string, unknown], @@ -102,8 +102,8 @@ export default class ModuleMap implements IModuleMap { duplicates: ModuleMap.mapToArrayRecursive( this._raw.duplicates, ) as SerializableModuleMap['duplicates'], - map: Array.from(this._raw.map), - mocks: Array.from(this._raw.mocks), + map: [...this._raw.map], + mocks: [...this._raw.mocks], rootDir: this._raw.rootDir, }; } @@ -224,9 +224,9 @@ class DuplicateHasteCandidatesError extends Error { 'cannot be resolved, because there exists several different ' + 'files, or packages, that provide a module for ' + `that particular name and platform. ${platformMessage} You must ` + - `delete or exclude files until there remains only one of these:\n\n${Array.from( - duplicatesSet, - ) + `delete or exclude files until there remains only one of these:\n\n${[ + ...duplicatesSet, + ] .map( ([dupFilePath, dupFileType]) => ` * \`${dupFilePath}\` (${getTypeMessage(dupFileType)})\n`, diff --git a/packages/jest-haste-map/src/__tests__/index.test.js b/packages/jest-haste-map/src/__tests__/index.test.js index e94ec8862d50..3787dbbd239e 100644 --- a/packages/jest-haste-map/src/__tests__/index.test.js +++ b/packages/jest-haste-map/src/__tests__/index.test.js @@ -130,7 +130,7 @@ const useBuitinsInContext = value => { switch (stringTag) { case '[object Map]': return new Map( - Array.from(value).map(([k, v]) => [ + [...value].map(([k, v]) => [ useBuitinsInContext(k), useBuitinsInContext(v), ]), diff --git a/packages/jest-haste-map/src/crawlers/node.ts b/packages/jest-haste-map/src/crawlers/node.ts index 320227906dda..d12aecb3f9b4 100644 --- a/packages/jest-haste-map/src/crawlers/node.ts +++ b/packages/jest-haste-map/src/crawlers/node.ts @@ -137,7 +137,7 @@ function findNative( enableSymlinks: boolean, callback: Callback, ): void { - const args = Array.from(roots); + const args = [...roots]; if (enableSymlinks) { args.push('(', '-type', 'f', '-o', '-type', 'l', ')'); } else { diff --git a/packages/jest-haste-map/src/crawlers/watchman.ts b/packages/jest-haste-map/src/crawlers/watchman.ts index ca943a3e938c..4fdf1d124b2b 100644 --- a/packages/jest-haste-map/src/crawlers/watchman.ts +++ b/packages/jest-haste-map/src/crawlers/watchman.ts @@ -156,10 +156,10 @@ export async function watchmanCrawl(options: CrawlerOptions): Promise<{ if (canBeFiltered) { if (response.relative_path) { - watchmanRoots.set( - response.watch, - (existing || []).concat(response.relative_path), - ); + watchmanRoots.set(response.watch, [ + ...(existing || []), + response.relative_path, + ]); } else { // Make the filter directories an empty array to signal that this // root was already seen and needs to be watched for all files or @@ -176,68 +176,62 @@ export async function watchmanCrawl(options: CrawlerOptions): Promise<{ const results = new Map(); let isFresh = false; await Promise.all( - Array.from(rootProjectDirMappings).map( - async ([root, directoryFilters]) => { - const expression = Array.from(defaultWatchExpression); - const glob = []; - - if (directoryFilters.length > 0) { - expression.push([ - 'anyof', - ...directoryFilters.map(dir => ['dirname', dir]), - ]); + [...rootProjectDirMappings].map(async ([root, directoryFilters]) => { + const expression = [...defaultWatchExpression]; + const glob = []; - for (const directory of directoryFilters) { - for (const extension of extensions) { - glob.push(`${directory}/**/*.${extension}`); - } - } - } else { + if (directoryFilters.length > 0) { + expression.push([ + 'anyof', + ...directoryFilters.map(dir => ['dirname', dir]), + ]); + + for (const directory of directoryFilters) { for (const extension of extensions) { - glob.push(`**/*.${extension}`); + glob.push(`${directory}/**/*.${extension}`); } } - - // Jest is only going to store one type of clock; a string that - // represents a local clock. However, the Watchman crawler supports - // a second type of clock that can be written by automation outside of - // Jest, called an "scm query", which fetches changed files based on - // source control mergebases. The reason this is necessary is because - // local clocks are not portable across systems, but scm queries are. - // By using scm queries, we can create the haste map on a different - // system and import it, transforming the clock into a local clock. - const since = clocks.get(fastPath.relative(rootDir, root)); - - const query = - since === undefined - ? // Use the `since` generator if we have a clock available - {expression, fields, glob, glob_includedotfiles: true} - : // Otherwise use the `glob` filter - {expression, fields, since}; - - const response = await cmd( - 'query', - root, - query, - ); - - if ('warning' in response) { - console.warn('watchman warning:', response.warning); + } else { + for (const extension of extensions) { + glob.push(`**/*.${extension}`); } + } - // When a source-control query is used, we ignore the "is fresh" - // response from Watchman because it will be true despite the query - // being incremental. - const isSourceControlQuery = - typeof since !== 'string' && - since?.scm?.['mergebase-with'] !== undefined; - if (!isSourceControlQuery) { - isFresh = isFresh || response.is_fresh_instance; - } + // Jest is only going to store one type of clock; a string that + // represents a local clock. However, the Watchman crawler supports + // a second type of clock that can be written by automation outside of + // Jest, called an "scm query", which fetches changed files based on + // source control mergebases. The reason this is necessary is because + // local clocks are not portable across systems, but scm queries are. + // By using scm queries, we can create the haste map on a different + // system and import it, transforming the clock into a local clock. + const since = clocks.get(fastPath.relative(rootDir, root)); + + const query = + since === undefined + ? // Use the `since` generator if we have a clock available + {expression, fields, glob, glob_includedotfiles: true} + : // Otherwise use the `glob` filter + {expression, fields, since}; + + const response = await cmd('query', root, query); + + if ('warning' in response) { + console.warn('watchman warning:', response.warning); + } - results.set(root, response); - }, - ), + // When a source-control query is used, we ignore the "is fresh" + // response from Watchman because it will be true despite the query + // being incremental. + const isSourceControlQuery = + typeof since !== 'string' && + since?.scm?.['mergebase-with'] !== undefined; + if (!isSourceControlQuery) { + isFresh = isFresh || response.is_fresh_instance; + } + + results.set(root, response); + }), ); return { diff --git a/packages/jest-haste-map/src/index.ts b/packages/jest-haste-map/src/index.ts index 3dcf5d5b1c12..354104331353 100644 --- a/packages/jest-haste-map/src/index.ts +++ b/packages/jest-haste-map/src/index.ts @@ -258,7 +258,7 @@ class HasteMap extends EventEmitter implements IHasteMap { resetCache: options.resetCache, retainAllFiles: options.retainAllFiles, rootDir: options.rootDir, - roots: Array.from(new Set(options.roots)), + roots: [...new Set(options.roots)], skipPackageJson: !!options.skipPackageJson, throwOnModuleCollision: !!options.throwOnModuleCollision, useWatchman: options.useWatchman ?? true, @@ -270,7 +270,7 @@ class HasteMap extends EventEmitter implements IHasteMap { if (options.ignorePattern) { if (options.ignorePattern instanceof RegExp) { this._options.ignorePattern = new RegExp( - options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), + `${options.ignorePattern.source}|${VCS_DIRECTORIES}`, options.ignorePattern.flags, ); } else { diff --git a/packages/jest-haste-map/src/worker.ts b/packages/jest-haste-map/src/worker.ts index dadcf1d8de13..699480a05929 100644 --- a/packages/jest-haste-map/src/worker.ts +++ b/packages/jest-haste-map/src/worker.ts @@ -83,13 +83,13 @@ export async function worker(data: WorkerMessage): Promise { false, ) : defaultDependencyExtractor; - dependencies = Array.from( - extractor.extract( + dependencies = [ + ...extractor.extract( content, filePath, defaultDependencyExtractor.extract, ), - ); + ]; } if (id) { diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index 09f575240981..16546e862a64 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -227,7 +227,7 @@ const addSnapshotData = (results: TestResult, snapshotState: SnapshotState) => { results.snapshot.updated = snapshotState.updated; results.snapshot.unchecked = status.deleted ? 0 : uncheckedCount; // Copy the array to prevent memory leaks - results.snapshot.uncheckedKeys = Array.from(uncheckedKeys); + results.snapshot.uncheckedKeys = [...uncheckedKeys]; return results; }; diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index b625350347c6..b2262cd10bf4 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -269,8 +269,8 @@ export default function jasmineEnv(j$: Jasmine) { let oldListenersRejection: Array; const executionSetup = function () { // Need to ensure we are the only ones handling these exceptions. - oldListenersException = process.listeners('uncaughtException').slice(); - oldListenersRejection = process.listeners('unhandledRejection').slice(); + oldListenersException = [...process.listeners('uncaughtException')]; + oldListenersRejection = [...process.listeners('unhandledRejection')]; j$.process.removeAllListeners('uncaughtException'); j$.process.removeAllListeners('unhandledRejection'); diff --git a/packages/jest-jasmine2/src/reporter.ts b/packages/jest-jasmine2/src/reporter.ts index 4769ee975b32..4182b370cc3d 100644 --- a/packages/jest-jasmine2/src/reporter.ts +++ b/packages/jest-jasmine2/src/reporter.ts @@ -52,7 +52,7 @@ export default class Jasmine2Reporter implements Reporter { specDone(result: SpecResult): void { this._testResults.push( - this._extractSpecResults(result, this._currentSuites.slice(0)), + this._extractSpecResults(result, [...this._currentSuites]), ); } diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index 33e6894ad957..da758fff003e 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -58,7 +58,10 @@ const addAssertionErrors = (result: SpecResult) => { passed: false, })); result.status = 'failed'; - result.failedExpectations = result.failedExpectations.concat(jasmineErrors); + result.failedExpectations = [ + ...result.failedExpectations, + ...jasmineErrors, + ]; } }; diff --git a/packages/jest-jasmine2/src/treeProcessor.ts b/packages/jest-jasmine2/src/treeProcessor.ts index d74d437b2005..dae3cde75c66 100644 --- a/packages/jest-jasmine2/src/treeProcessor.ts +++ b/packages/jest-jasmine2/src/treeProcessor.ts @@ -80,7 +80,7 @@ export default function treeProcessor(options: Options): void { if (hasNoEnabledTest(node)) { return children; } - return node.beforeAllFns.concat(children).concat(node.afterAllFns); + return [...node.beforeAllFns, ...children, ...node.afterAllFns]; } const treeHandler = getNodeHandler(tree, false); diff --git a/packages/jest-mock/src/index.ts b/packages/jest-mock/src/index.ts index dc17fe1ed769..6cdfda373841 100644 --- a/packages/jest-mock/src/index.ts +++ b/packages/jest-mock/src/index.ts @@ -545,7 +545,7 @@ export class ModuleMocker { object = Object.getPrototypeOf(object); } - return Array.from(slots); + return [...slots]; } private _ensureMockConfig(f: Mock): MockFunctionConfig { diff --git a/packages/jest-reporters/src/CoverageReporter.ts b/packages/jest-reporters/src/CoverageReporter.ts index 6b8ab05076cd..94a39bcc01fc 100644 --- a/packages/jest-reporters/src/CoverageReporter.ts +++ b/packages/jest-reporters/src/CoverageReporter.ts @@ -169,12 +169,13 @@ export default class CoverageReporter extends BaseReporter { const result = await worker.worker({ config, context: { - changedFiles: - this._context.changedFiles && - Array.from(this._context.changedFiles), - sourcesRelatedToTestsInChangedFiles: - this._context.sourcesRelatedToTestsInChangedFiles && - Array.from(this._context.sourcesRelatedToTestsInChangedFiles), + changedFiles: this._context.changedFiles && [ + ...this._context.changedFiles, + ], + sourcesRelatedToTestsInChangedFiles: this._context + .sourcesRelatedToTestsInChangedFiles && [ + ...this._context.sourcesRelatedToTestsInChangedFiles, + ], }, globalConfig: this._globalConfig, path: filename, @@ -286,7 +287,7 @@ export default class CoverageReporter extends BaseReporter { if (file.indexOf(absoluteThresholdGroup) === 0) { groupTypeByThresholdGroup[thresholdGroup] = THRESHOLD_GROUP_TYPES.PATH; - return agg.concat([[file, thresholdGroup]]); + return [...agg, [file, thresholdGroup]]; } // If the threshold group is not a path it might be a glob: @@ -303,25 +304,25 @@ export default class CoverageReporter extends BaseReporter { if (filesByGlob[absoluteThresholdGroup].includes(file)) { groupTypeByThresholdGroup[thresholdGroup] = THRESHOLD_GROUP_TYPES.GLOB; - return agg.concat([[file, thresholdGroup]]); + return [...agg, [file, thresholdGroup]]; } return agg; }, []); if (pathOrGlobMatches.length > 0) { - return files.concat(pathOrGlobMatches); + return [...files, ...pathOrGlobMatches]; } // Neither a glob or a path? Toss it in global if there's a global threshold: if (thresholdGroups.includes(THRESHOLD_GROUP_TYPES.GLOBAL)) { groupTypeByThresholdGroup[THRESHOLD_GROUP_TYPES.GLOBAL] = THRESHOLD_GROUP_TYPES.GLOBAL; - return files.concat([[file, THRESHOLD_GROUP_TYPES.GLOBAL]]); + return [...files, [file, THRESHOLD_GROUP_TYPES.GLOBAL]]; } // A covered file that doesn't have a threshold: - return files.concat([[file, undefined]]); + return [...files, [file, undefined]]; }, []); const getFilesInThresholdGroup = (thresholdGroup: string) => @@ -358,13 +359,14 @@ export default class CoverageReporter extends BaseReporter { getFilesInThresholdGroup(THRESHOLD_GROUP_TYPES.GLOBAL), ); if (coverage) { - errors = errors.concat( - check( + errors = [ + ...errors, + ...check( thresholdGroup, coverageThreshold[thresholdGroup], coverage, ), - ); + ]; } break; } @@ -373,13 +375,14 @@ export default class CoverageReporter extends BaseReporter { getFilesInThresholdGroup(thresholdGroup), ); if (coverage) { - errors = errors.concat( - check( + errors = [ + ...errors, + ...check( thresholdGroup, coverageThreshold[thresholdGroup], coverage, ), - ); + ]; } break; } @@ -387,22 +390,24 @@ export default class CoverageReporter extends BaseReporter { for (const fileMatchingGlob of getFilesInThresholdGroup( thresholdGroup, )) { - errors = errors.concat( - check( + errors = [ + ...errors, + ...check( fileMatchingGlob, coverageThreshold[thresholdGroup], map.fileCoverageFor(fileMatchingGlob).toSummary(), ), - ); + ]; } break; default: // If the file specified by path is not found, error is returned. if (thresholdGroup !== THRESHOLD_GROUP_TYPES.GLOBAL) { - errors = errors.concat( + errors = [ + ...errors, `Jest: Coverage data for ${thresholdGroup} was not found.`, - ); + ]; } // Sometimes all files in the coverage data are matched by // PATH and GLOB threshold groups in which case, don't error when diff --git a/packages/jest-resolve-dependencies/src/index.ts b/packages/jest-resolve-dependencies/src/index.ts index f842c6e1e243..2057367291a1 100644 --- a/packages/jest-resolve-dependencies/src/index.ts +++ b/packages/jest-resolve-dependencies/src/index.ts @@ -133,9 +133,10 @@ export class DependencyResolver { }, []), ); } - return result.concat( - Array.from(related).map(file => ({dependencies: [], file})), - ); + return [ + ...result, + ...[...related].map(file => ({dependencies: [], file})), + ]; }; const relatedPaths = new Set(); diff --git a/packages/jest-resolve/src/__tests__/resolve.test.ts b/packages/jest-resolve/src/__tests__/resolve.test.ts index 0c557816bf41..b7408dc8cd07 100644 --- a/packages/jest-resolve/src/__tests__/resolve.test.ts +++ b/packages/jest-resolve/src/__tests__/resolve.test.ts @@ -128,7 +128,7 @@ describe('findNodeModule', () => { defaultResolver, extensions: ['js'], moduleDirectory: ['node_modules'], - paths: (nodePaths || []).concat(['/something']), + paths: [...(nodePaths || []), '/something'], rootDir: undefined, }); }); @@ -431,7 +431,7 @@ describe('findNodeModuleAsync', () => { defaultResolver, extensions: ['js'], moduleDirectory: ['node_modules'], - paths: (nodePaths || []).concat(['/something']), + paths: [...(nodePaths || []), '/something'], rootDir: undefined, }); }); diff --git a/packages/jest-resolve/src/nodeModulesPaths.ts b/packages/jest-resolve/src/nodeModulesPaths.ts index bccadae34025..7bcad180f758 100644 --- a/packages/jest-resolve/src/nodeModulesPaths.ts +++ b/packages/jest-resolve/src/nodeModulesPaths.ts @@ -21,7 +21,7 @@ export default function nodeModulesPaths( ): Array { const modules = options && options.moduleDirectory - ? Array.from(options.moduleDirectory) + ? [...options.moduleDirectory] : ['node_modules']; // ensure that `basedir` is an absolute path at this point, diff --git a/packages/jest-resolve/src/resolver.ts b/packages/jest-resolve/src/resolver.ts index 13a724e011b0..4efcf3aaa9c2 100644 --- a/packages/jest-resolve/src/resolver.ts +++ b/packages/jest-resolve/src/resolver.ts @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -/* eslint-disable local/prefer-spread-eventually */ - import * as path from 'path'; import chalk = require('chalk'); import slash = require('slash'); @@ -127,7 +125,7 @@ export default class Resolver { defaultResolver, extensions: options.extensions, moduleDirectory: options.moduleDirectory, - paths: paths ? (nodePaths || []).concat(paths) : nodePaths, + paths: paths ? [...(nodePaths || []), ...paths] : nodePaths, rootDir: options.rootDir, }); } catch (error) { @@ -170,7 +168,7 @@ export default class Resolver { defaultResolver, extensions: options.extensions, moduleDirectory: options.moduleDirectory, - paths: paths ? (nodePaths || []).concat(paths) : nodePaths, + paths: paths ? [...(nodePaths || []), ...paths] : nodePaths, rootDir: options.rootDir, }); return result; @@ -393,7 +391,7 @@ export default class Resolver { const stringifiedOptions = options ? JSON.stringify(options) : ''; const key = dirname + path.delimiter + moduleName + stringifiedOptions; const defaultPlatform = this._options.defaultPlatform; - const extensions = this._options.extensions.slice(); + const extensions = [...this._options.extensions]; if (this._supportsNativePlatform) { extensions.unshift( @@ -419,7 +417,7 @@ export default class Resolver { const parts = moduleName.split('/'); const hastePackage = this.getPackage(parts.shift()!); if (hastePackage) { - return path.join.apply(path, [path.dirname(hastePackage)].concat(parts)); + return path.join(path.dirname(hastePackage), ...parts); } return null; } diff --git a/packages/jest-runner/src/index.ts b/packages/jest-runner/src/index.ts index e4bf2ea166e2..6b7f305ff07b 100644 --- a/packages/jest-runner/src/index.ts +++ b/packages/jest-runner/src/index.ts @@ -117,7 +117,7 @@ export default class TestRunner extends EmittingTestRunner { : undefined, maxRetries: 3, numWorkers: this._globalConfig.maxWorkers, - setupArgs: [{serializableResolvers: Array.from(resolvers.values())}], + setupArgs: [{serializableResolvers: [...resolvers.values()]}], }) as JestWorkerFarm; if (worker.getStdout()) worker.getStdout().pipe(process.stdout); @@ -139,12 +139,13 @@ export default class TestRunner extends EmittingTestRunner { config: test.context.config, context: { ...this._context, - changedFiles: - this._context.changedFiles && - Array.from(this._context.changedFiles), - sourcesRelatedToTestsInChangedFiles: - this._context.sourcesRelatedToTestsInChangedFiles && - Array.from(this._context.sourcesRelatedToTestsInChangedFiles), + changedFiles: this._context.changedFiles && [ + ...this._context.changedFiles, + ], + sourcesRelatedToTestsInChangedFiles: this._context + .sourcesRelatedToTestsInChangedFiles && [ + ...this._context.sourcesRelatedToTestsInChangedFiles, + ], }, globalConfig: this._globalConfig, path: test.path, diff --git a/packages/jest-runtime/src/__tests__/Runtime-statics.test.js b/packages/jest-runtime/src/__tests__/Runtime-statics.test.js index 1b8672a31017..aa9120ae7d6a 100644 --- a/packages/jest-runtime/src/__tests__/Runtime-statics.test.js +++ b/packages/jest-runtime/src/__tests__/Runtime-statics.test.js @@ -6,18 +6,19 @@ * */ +import {makeProjectConfig} from '@jest/test-utils'; import HasteMap from 'jest-haste-map'; import Runtime from '../'; jest.mock('jest-haste-map'); describe('Runtime statics', () => { - const projectConfig = { + const projectConfig = makeProjectConfig({ cacheDirectory: '/tmp', haste: {}, modulePathIgnorePatterns: ['/root/ignore-1', '/root/ignore-2'], watchPathIgnorePatterns: ['/watch-root/ignore-1'], - }; + }); const options = {}; beforeEach(() => { diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index c5d1e2cb9c11..db72eafb1e63 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -283,12 +283,12 @@ export default class Runtime { const envExportConditions = this._environment.exportConditions?.() ?? []; - this.esmConditions = Array.from( - new Set(['import', 'default', ...envExportConditions]), - ); - this.cjsConditions = Array.from( - new Set(['require', 'default', ...envExportConditions]), - ); + this.esmConditions = [ + ...new Set(['import', 'default', ...envExportConditions]), + ]; + this.cjsConditions = [ + ...new Set(['require', 'default', ...envExportConditions]), + ]; if (config.automock) { for (const filePath of config.setupFiles) { @@ -362,7 +362,7 @@ export default class Runtime { console: options?.console, dependencyExtractor: config.dependencyExtractor, enableSymlinks: config.haste.enableSymlinks, - extensions: [SnapshotExtension].concat(config.moduleFileExtensions), + extensions: [SnapshotExtension, ...config.moduleFileExtensions], forceNodeFilesystemAPI: config.haste.forceNodeFilesystemAPI, hasteImplModulePath: config.haste.hasteImplModulePath, hasteMapModulePath: config.haste.hasteMapModulePath, @@ -1304,7 +1304,7 @@ export default class Runtime { res.url, this._coverageOptions, this._config, - /* loadedFilenames */ Array.from(this._v8CoverageSources!.keys()), + /* loadedFilenames */ [...this._v8CoverageSources!.keys()], ), ) .map(result => { @@ -2101,7 +2101,7 @@ export default class Runtime { }, has: (_target, key) => typeof key === 'string' && this._moduleRegistry.has(key), - ownKeys: () => Array.from(this._moduleRegistry.keys()), + ownKeys: () => [...this._moduleRegistry.keys()], set: notPermittedMethod, }); })(); diff --git a/packages/jest-snapshot/src/State.ts b/packages/jest-snapshot/src/State.ts index 0403a96129ac..b58e5931edbf 100644 --- a/packages/jest-snapshot/src/State.ts +++ b/packages/jest-snapshot/src/State.ts @@ -180,7 +180,7 @@ export default class SnapshotState { } getUncheckedKeys(): Array { - return Array.from(this._uncheckedKeys); + return [...this._uncheckedKeys]; } removeUncheckedKeys(): void { diff --git a/packages/jest-snapshot/src/__tests__/plugins.test.ts b/packages/jest-snapshot/src/__tests__/plugins.test.ts index 2ffd3f834474..a091550e5bab 100644 --- a/packages/jest-snapshot/src/__tests__/plugins.test.ts +++ b/packages/jest-snapshot/src/__tests__/plugins.test.ts @@ -21,11 +21,11 @@ const testPath = (names: Array) => { // Jest tests snapshotSerializers in order preceding built-in serializers. // Therefore, add in reverse because the last added is the first tested. - for (const serializer of added.concat().reverse()) addSerializer(serializer); + for (const serializer of [...added].reverse()) addSerializer(serializer); const next = getSerializers(); expect(next).toHaveLength(added.length + prev.length); - expect(next).toEqual(added.concat(prev)); + expect(next).toEqual([...added, ...prev]); }; it('gets plugins', () => { diff --git a/packages/jest-snapshot/src/plugins.ts b/packages/jest-snapshot/src/plugins.ts index bc62647d3c4e..cc3118c61555 100644 --- a/packages/jest-snapshot/src/plugins.ts +++ b/packages/jest-snapshot/src/plugins.ts @@ -33,7 +33,7 @@ let PLUGINS: PrettyFormatPlugins = [ // Prepend to list so the last added is the first tested. export const addSerializer = (plugin: PrettyFormatPlugin): void => { - PLUGINS = [plugin].concat(PLUGINS); + PLUGINS = [plugin, ...PLUGINS]; }; export const getSerializers = (): PrettyFormatPlugins => PLUGINS; diff --git a/packages/jest-snapshot/src/utils.ts b/packages/jest-snapshot/src/utils.ts index 84b2b5194e5c..4ee0255f4a2c 100644 --- a/packages/jest-snapshot/src/utils.ts +++ b/packages/jest-snapshot/src/utils.ts @@ -234,7 +234,7 @@ const isAnyOrAnything = (input: object) => ['Any', 'Anything'].includes(input.constructor.name); const deepMergeArray = (target: Array, source: Array) => { - const mergedOutput = Array.from(target); + const mergedOutput = [...target]; for (const [index, sourceElement] of source.entries()) { const targetElement = mergedOutput[index]; @@ -496,7 +496,10 @@ const groupSnapshotsBy = snapshots.reduce>>( (object, inlineSnapshot) => { const key = createKey(inlineSnapshot); - return {...object, [key]: (object[key] || []).concat(inlineSnapshot)}; + return { + ...object, + [key]: [...(object[key] || []), inlineSnapshot], + }; }, {}, ); diff --git a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts index 2c4e6012a494..1222353730a3 100644 --- a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts +++ b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts @@ -2062,7 +2062,7 @@ describe('ScriptTransformer', () => { }); // @ts-expect-error - private property - expect(Array.from(scriptTransformer._transformCache.entries())).toEqual([ + expect([...scriptTransformer._transformCache.entries()]).toEqual([ ['\\.js$test_preprocessor', expect.any(Object)], ]); }); diff --git a/packages/jest-validate/src/errors.ts b/packages/jest-validate/src/errors.ts index 1a40218c8b74..2f14a0ff0fc7 100644 --- a/packages/jest-validate/src/errors.ts +++ b/packages/jest-validate/src/errors.ts @@ -19,9 +19,7 @@ export const errorMessage = ( path?: Array, ): void => { const conditions = getValues(defaultValue); - const validTypes: Array = Array.from( - new Set(conditions.map(getType)), - ); + const validTypes: Array = [...new Set(conditions.map(getType))]; const message = ` Option ${chalk.bold( `"${path && path.length > 0 ? `${path.join('.')}.` : ''}${option}"`, diff --git a/packages/jest-validate/src/validateCLIOptions.ts b/packages/jest-validate/src/validateCLIOptions.ts index e779e4a2e7e7..e26ea3adbd12 100644 --- a/packages/jest-validate/src/validateCLIOptions.ts +++ b/packages/jest-validate/src/validateCLIOptions.ts @@ -40,7 +40,7 @@ const createCLIValidationError = ( const unrecognized = unrecognizedOptions[0]; const didYouMeanMessage = unrecognized.length > 1 - ? createDidYouMeanMessage(unrecognized, Array.from(allowedOptions)) + ? createDidYouMeanMessage(unrecognized, [...allowedOptions]) : ''; message = ` Unrecognized option ${chalk.bold(format(unrecognized))}.${ didYouMeanMessage ? ` ${didYouMeanMessage}` : '' diff --git a/packages/pretty-format/src/index.ts b/packages/pretty-format/src/index.ts index 8eb3b37b68ad..a391008b6ac8 100644 --- a/packages/pretty-format/src/index.ts +++ b/packages/pretty-format/src/index.ts @@ -210,7 +210,7 @@ function printComplexValue( if (refs.includes(val)) { return '[Circular]'; } - refs = refs.slice(); + refs = [...refs]; refs.push(val); const hitMaxDepth = ++depth > config.maxDepth; diff --git a/packages/pretty-format/src/plugins/DOMCollection.ts b/packages/pretty-format/src/plugins/DOMCollection.ts index a6ccd9aec3a9..3e040cb71380 100644 --- a/packages/pretty-format/src/plugins/DOMCollection.ts +++ b/packages/pretty-format/src/plugins/DOMCollection.ts @@ -43,7 +43,7 @@ export const serialize: NewPlugin['serialize'] = ( (OBJECT_NAMES.has(name) ? `{${printObjectProperties( isNamedNodeMap(collection) - ? Array.from(collection).reduce>( + ? [...collection].reduce>( (props, attribute) => { props[attribute.name] = attribute.value; return props; @@ -58,7 +58,7 @@ export const serialize: NewPlugin['serialize'] = ( printer, )}}` : `[${printListItems( - Array.from(collection), + [...collection], config, indentation, depth, diff --git a/packages/pretty-format/src/plugins/DOMElement.ts b/packages/pretty-format/src/plugins/DOMElement.ts index b661005c8b6e..ca2fe9631d47 100644 --- a/packages/pretty-format/src/plugins/DOMElement.ts +++ b/packages/pretty-format/src/plugins/DOMElement.ts @@ -95,7 +95,7 @@ export const serialize: NewPlugin['serialize'] = ( : Array.from(node.attributes, attr => attr.name).sort(), nodeIsFragment(node) ? {} - : Array.from(node.attributes).reduce>( + : [...node.attributes].reduce>( (props, attribute) => { props[attribute.name] = attribute.value; return props; diff --git a/packages/test-utils/src/config.ts b/packages/test-utils/src/config.ts index 9531ebbffc89..b3e22501cc8e 100644 --- a/packages/test-utils/src/config.ts +++ b/packages/test-utils/src/config.ts @@ -140,13 +140,14 @@ export const makeGlobalConfig = ( overrides: Partial = {}, ): Config.GlobalConfig => { const overridesKeys = new Set(Object.keys(overrides)); - for (const key of Object.keys(DEFAULT_GLOBAL_CONFIG)) + for (const key of Object.keys(DEFAULT_GLOBAL_CONFIG)) { overridesKeys.delete(key); + } if (overridesKeys.size > 0) { throw new Error(` Properties that are not part of GlobalConfig type were passed: - ${JSON.stringify(Array.from(overridesKeys))} + ${JSON.stringify([...overridesKeys])} `); } @@ -157,13 +158,14 @@ export const makeProjectConfig = ( overrides: Partial = {}, ): Config.ProjectConfig => { const overridesKeys = new Set(Object.keys(overrides)); - for (const key of Object.keys(DEFAULT_PROJECT_CONFIG)) + for (const key of Object.keys(DEFAULT_PROJECT_CONFIG)) { overridesKeys.delete(key); + } if (overridesKeys.size > 0) { throw new Error(` Properties that are not part of ProjectConfig type were passed: - ${JSON.stringify(Array.from(overridesKeys))} + ${JSON.stringify([...overridesKeys])} `); } diff --git a/scripts/buildTs.mjs b/scripts/buildTs.mjs index 191da7feb6dc..bdd931651815 100644 --- a/scripts/buildTs.mjs +++ b/scripts/buildTs.mjs @@ -41,8 +41,10 @@ for (const {packageDir, pkg} of packagesWithTs) { `\`main\` and \`types\` field of ${pkg.name} does not match`, ); - const jestDependenciesOfPackage = Object.keys(pkg.dependencies || {}) - .concat(Object.keys(pkg.devDependencies || {})) + const jestDependenciesOfPackage = [ + ...Object.keys(pkg.dependencies || {}), + ...Object.keys(pkg.devDependencies || {}), + ] .filter(dep => { if (!workspacesWithTs.has(dep)) { return false; diff --git a/scripts/buildUtils.mjs b/scripts/buildUtils.mjs index d82ef74e5768..c428829260b6 100644 --- a/scripts/buildUtils.mjs +++ b/scripts/buildUtils.mjs @@ -161,7 +161,7 @@ export function createBuildConfigs() { } const options = Object.assign({}, babelConfig); - options.plugins = options.plugins.slice(); + options.plugins = [...options.plugins]; if (INLINE_REQUIRE_EXCLUDE_LIST.test(input)) { // The excluded modules are injected into the user's sandbox diff --git a/scripts/verifyOldTs.mjs b/scripts/verifyOldTs.mjs index f3f79a3bd19c..8b80ceb4d85c 100644 --- a/scripts/verifyOldTs.mjs +++ b/scripts/verifyOldTs.mjs @@ -219,7 +219,7 @@ function typeTests() { return entries[0][1].locator; }); - return Array.from(new Set(locators)); + return [...new Set(locators)]; } } diff --git a/website/src/prism/themeDark.js b/website/src/prism/themeDark.js index b9b01adc486e..d81f185ac6f4 100644 --- a/website/src/prism/themeDark.js +++ b/website/src/prism/themeDark.js @@ -59,5 +59,5 @@ module.exports = { backgroundColor: '#242526', color: '#eee', }, - styles: baseTheme.styles.concat(themeDark), + styles: [...baseTheme.styles, ...themeDark], }; diff --git a/website/src/prism/themeLight.js b/website/src/prism/themeLight.js index 885461491358..610ff8a075f3 100644 --- a/website/src/prism/themeLight.js +++ b/website/src/prism/themeLight.js @@ -56,5 +56,5 @@ const themeLight = [ module.exports = { plain: Object.assign(baseTheme.plain, {backgroundColor: '#f6f6f6'}), - styles: baseTheme.styles.concat(themeLight), + styles: [...baseTheme.styles, ...themeLight], }; diff --git a/website/versioned_docs/version-29.4/Configuration.md b/website/versioned_docs/version-29.4/Configuration.md index ae6fbc3a62b6..97f0eec0bbfd 100644 --- a/website/versioned_docs/version-29.4/Configuration.md +++ b/website/versioned_docs/version-29.4/Configuration.md @@ -2126,7 +2126,7 @@ class CustomSequencer extends Sequencer { sort(tests) { // Test structure information // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 - const copyTests = Array.from(tests); + const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } } diff --git a/website/versioned_docs/version-29.5/Configuration.md b/website/versioned_docs/version-29.5/Configuration.md index aac9ba23ce49..acd25605bfaf 100644 --- a/website/versioned_docs/version-29.5/Configuration.md +++ b/website/versioned_docs/version-29.5/Configuration.md @@ -2161,7 +2161,7 @@ class CustomSequencer extends Sequencer { sort(tests) { // Test structure information // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 - const copyTests = Array.from(tests); + const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } } diff --git a/website/versioned_docs/version-29.6/Configuration.md b/website/versioned_docs/version-29.6/Configuration.md index 168953702904..319334091dd7 100644 --- a/website/versioned_docs/version-29.6/Configuration.md +++ b/website/versioned_docs/version-29.6/Configuration.md @@ -2197,7 +2197,7 @@ class CustomSequencer extends Sequencer { sort(tests) { // Test structure information // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 - const copyTests = Array.from(tests); + const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } } diff --git a/website/versioned_docs/version-29.7/Configuration.md b/website/versioned_docs/version-29.7/Configuration.md index 168953702904..319334091dd7 100644 --- a/website/versioned_docs/version-29.7/Configuration.md +++ b/website/versioned_docs/version-29.7/Configuration.md @@ -2197,7 +2197,7 @@ class CustomSequencer extends Sequencer { sort(tests) { // Test structure information // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 - const copyTests = Array.from(tests); + const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } }