From c13bca305508716ca99552b5c32a884ce090fecf Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Sun, 31 Dec 2023 18:38:00 +0100 Subject: [PATCH] chore: use `String.replaceAll` if possible (#14823) --- .eslintrc.cjs | 3 --- e2e/Utils.ts | 12 +++++------ e2e/__tests__/beforeAllFiltered.ts | 2 +- e2e/__tests__/beforeEachQueue.ts | 2 +- e2e/__tests__/customEsmTestSequencers.test.ts | 2 +- e2e/__tests__/customTestSequencers.test.ts | 10 +++++----- e2e/__tests__/declarationErrors.test.ts | 2 +- e2e/__tests__/dependencyClash.test.ts | 2 +- e2e/__tests__/failureDetailsProperty.test.ts | 2 +- e2e/__tests__/failures.test.ts | 8 ++++---- e2e/__tests__/globals.test.ts | 2 +- e2e/__tests__/jest.config.js.test.ts | 2 +- e2e/__tests__/jest.config.ts.test.ts | 2 +- e2e/__tests__/multipleConfigs.ts | 2 +- e2e/__tests__/showConfig.test.ts | 20 +++++++++---------- e2e/__tests__/watchModeUpdateSnapshot.test.ts | 2 +- e2e/coverage-handlebars/__tests__/greet.js | 2 +- packages/expect-utils/src/utils.ts | 2 +- packages/expect/src/print.ts | 2 +- packages/expect/src/spyMatchers.ts | 2 +- packages/expect/tsconfig.json | 2 +- .../jest-circus/src/__mocks__/testUtils.ts | 10 +++++----- .../jest-circus/src/formatNodeAssertErrors.ts | 2 +- packages/jest-config/src/Deprecated.ts | 2 +- packages/jest-config/src/normalize.ts | 2 +- packages/jest-config/src/utils.ts | 2 +- packages/jest-console/src/BufferedConsole.ts | 2 +- packages/jest-console/src/CustomConsole.ts | 2 +- packages/jest-core/src/SearchSource.ts | 2 +- packages/jest-docblock/src/index.ts | 8 ++++---- packages/jest-each/src/bind.ts | 2 +- packages/jest-each/src/table/array.ts | 11 ++++++---- packages/jest-each/src/table/interpolation.ts | 2 +- packages/jest-fake-timers/tsconfig.json | 2 +- .../src/__tests__/dependencyExtractor.js | 6 +++--- .../src/__tests__/get_mock_name.test.js | 2 +- .../src/__tests__/index.test.js | 10 ++++++---- .../src/crawlers/__tests__/node.test.js | 2 +- .../src/crawlers/__tests__/watchman.test.js | 2 +- packages/jest-haste-map/src/getMockName.ts | 2 +- packages/jest-haste-map/src/index.ts | 2 +- .../src/lib/dependencyExtractor.ts | 4 ++-- .../src/lib/normalizePathSep.ts | 2 +- .../src/assertionErrorMessage.ts | 2 +- packages/jest-matcher-utils/src/index.ts | 4 ++-- packages/jest-matcher-utils/tsconfig.json | 2 +- packages/jest-message-util/src/index.ts | 2 +- packages/jest-mock/src/index.ts | 2 +- packages/jest-regex-util/src/index.ts | 6 +++--- .../src/GitHubActionsReporter.ts | 5 ++++- .../src/__tests__/SummaryReporter.test.js | 10 +++++----- .../src/__tests__/getSnapshotSummary.test.js | 6 +++--- packages/jest-resolve/src/resolver.ts | 2 +- packages/jest-snapshot/src/utils.ts | 7 ++++--- .../jest-transform/src/ScriptTransformer.ts | 2 +- .../src/__tests__/ScriptTransformer.test.ts | 2 +- .../jest-util/src/replacePathSepForGlob.ts | 2 +- .../src/__tests__/__fixtures__/jestConfig.ts | 2 +- .../src/lib/formatTestNameByPattern.ts | 2 +- .../src/__tests__/AsymmetricMatcher.test.ts | 4 ++-- .../src/__tests__/Immutable.test.ts | 18 +++++++++++------ .../src/__tests__/prettyFormat.test.ts | 4 ++-- .../src/__tests__/react.test.tsx | 4 ++-- packages/pretty-format/src/index.ts | 6 +++--- .../src/plugins/lib/escapeHTML.ts | 2 +- packages/pretty-format/tsconfig.json | 2 +- packages/test-utils/src/normalizeIcons.ts | 4 ++-- scripts/bundleTs.mjs | 2 +- 68 files changed, 141 insertions(+), 129 deletions(-) diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 687f71342da9..dc815e3b5f8e 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -697,9 +697,6 @@ module.exports = { 'unicorn/filename-case': 'off', 'unicorn/prefer-reflect-apply': 'off', - // TODO: turn on at some point - 'unicorn/prefer-string-replace-all': 'off', - // enabling this is blocked by https://github.com/microsoft/rushstack/issues/2780 'unicorn/prefer-export-from': 'off', // enabling this is blocked by https://github.com/jestjs/jest/pull/14297 diff --git a/e2e/Utils.ts b/e2e/Utils.ts index 11f542a22e8b..49d8989279c3 100644 --- a/e2e/Utils.ts +++ b/e2e/Utils.ts @@ -93,7 +93,7 @@ export const linkJestPackage = (packageName: string, cwd: string) => { export const makeTemplate = (str: string): ((values?: Array) => string) => (values = []) => - str.replace(/\$(\d+)/g, (_match, number) => { + str.replaceAll(/\$(\d+)/g, (_match, number) => { if (!Array.isArray(values)) { throw new TypeError('Array of values must be passed to the template.'); } @@ -191,12 +191,12 @@ export const copyDir = (src: string, dest: string) => { }; export const replaceSeed = (str: string) => - str.replace(/Seed: {8}(-?\d+)/g, 'Seed: <>'); + str.replaceAll(/Seed: {8}(-?\d+)/g, 'Seed: <>'); export const replaceTime = (str: string) => str - .replace(/\d*\.?\d+ m?s\b/g, '<>') - .replace(/, estimated <>/g, ''); + .replaceAll(/\d*\.?\d+ m?s\b/g, '<>') + .replaceAll(', estimated <>', ''); // Since Jest does not guarantee the order of tests we'll sort the output. export const sortLines = (output: string) => @@ -235,7 +235,7 @@ export const createEmptyPackage = ( export const extractSummary = (stdout: string) => { const match = stdout - .replace(/(?:\\[nr])+/g, '\n') + .replaceAll(/(?:\\[nr])+/g, '\n') .match( /(Seed:.*\n)?Test Suites:.*\nTests.*\nSnapshots.*\nTime.*(\nRan all test suites)*.*\n*$/gm, ); @@ -252,7 +252,7 @@ export const extractSummary = (stdout: string) => { const rest = stdout .replace(match[0], '') // remove all timestamps - .replace(/\s*\(\d*\.?\d+ m?s\b\)$/gm, ''); + .replaceAll(/\s*\(\d*\.?\d+ m?s\b\)$/gm, ''); return { rest: rest.trim(), diff --git a/e2e/__tests__/beforeAllFiltered.ts b/e2e/__tests__/beforeAllFiltered.ts index 6c96dbc2bc72..a4e50777a765 100644 --- a/e2e/__tests__/beforeAllFiltered.ts +++ b/e2e/__tests__/beforeAllFiltered.ts @@ -12,7 +12,7 @@ describe('Correct BeforeAll run', () => { let {stdout} = runJest('before-all-filtered'); // for some reason Circus does not have the `Object` part - stdout = stdout.replace(/at Object.log \(/g, 'at log ('); + stdout = stdout.replaceAll(/at Object.log \(/g, 'at log ('); expect(stdout).toMatchSnapshot(); }); diff --git a/e2e/__tests__/beforeEachQueue.ts b/e2e/__tests__/beforeEachQueue.ts index 280195d9893e..06a9f1a180e8 100644 --- a/e2e/__tests__/beforeEachQueue.ts +++ b/e2e/__tests__/beforeEachQueue.ts @@ -13,6 +13,6 @@ skipSuiteOnJestCircus(); // Circus does not support funky async definitions describe('Correct beforeEach order', () => { it('ensures the correct order for beforeEach', () => { const result = runJest('before-each-queue'); - expect(result.stdout.replace(/\\/g, '/')).toMatchSnapshot(); + expect(result.stdout.replaceAll('\\', '/')).toMatchSnapshot(); }); }); diff --git a/e2e/__tests__/customEsmTestSequencers.test.ts b/e2e/__tests__/customEsmTestSequencers.test.ts index 615a79cd8788..398c4090e680 100644 --- a/e2e/__tests__/customEsmTestSequencers.test.ts +++ b/e2e/__tests__/customEsmTestSequencers.test.ts @@ -17,7 +17,7 @@ test('run prioritySequence', () => { expect(result.exitCode).toBe(0); const sequence = extractSummary(result.stderr) - .rest.replace(/PASS /g, '') + .rest.replaceAll('PASS ', '') .split('\n'); expect(sequence).toEqual([ './a.test.js', diff --git a/e2e/__tests__/customTestSequencers.test.ts b/e2e/__tests__/customTestSequencers.test.ts index 575822f9b8ac..997533ac7763 100644 --- a/e2e/__tests__/customTestSequencers.test.ts +++ b/e2e/__tests__/customTestSequencers.test.ts @@ -24,7 +24,7 @@ test('run prioritySequence first sync', () => { ); expect(result.exitCode).toBe(0); const sequence = extractSummary(result.stderr) - .rest.replace(/PASS /g, '') + .rest.replaceAll('PASS ', '') .split('\n'); expect(sequence).toEqual([ './a.test.js', @@ -49,7 +49,7 @@ test('run prioritySequence first async', () => { ); expect(result.exitCode).toBe(0); const sequence = extractSummary(result.stderr) - .rest.replace(/PASS /g, '') + .rest.replaceAll('PASS ', '') .split('\n'); expect(sequence).toEqual([ './a.test.js', @@ -75,7 +75,7 @@ test('run failed tests async', () => { ); expect(result.exitCode).toBe(0); const sequence = extractSummary(result.stderr) - .rest.replace(/PASS /g, '') + .rest.replaceAll('PASS ', '') .split('\n'); expect(sequence).toEqual(['./c.test.js', './d.test.js']); }); @@ -95,7 +95,7 @@ test('run tests based on even seed', () => { ); expect(result.exitCode).toBe(0); const sequence = extractSummary(result.stderr) - .rest.replace(/PASS /g, '') + .rest.replaceAll('PASS ', '') .split('\n'); expect(sequence).toEqual([ './a.test.js', @@ -121,7 +121,7 @@ test('run tests based on odd seed', () => { ); expect(result.exitCode).toBe(0); const sequence = extractSummary(result.stderr) - .rest.replace(/PASS /g, '') + .rest.replaceAll('PASS ', '') .split('\n'); expect(sequence).toEqual([ './e.test.js', diff --git a/e2e/__tests__/declarationErrors.test.ts b/e2e/__tests__/declarationErrors.test.ts index 16a0793dc15f..726e85be3786 100644 --- a/e2e/__tests__/declarationErrors.test.ts +++ b/e2e/__tests__/declarationErrors.test.ts @@ -10,7 +10,7 @@ import runJest from '../runJest'; const extractMessage = (str: string) => extractSummary(str) - .rest.replace( + .rest.replaceAll( // circus-jasmine normalization /.+addSpecsToSuite (.+:\d+:\d+).+\n/g, '', diff --git a/e2e/__tests__/dependencyClash.test.ts b/e2e/__tests__/dependencyClash.test.ts index 4783514805f0..42abcd96d7e8 100644 --- a/e2e/__tests__/dependencyClash.test.ts +++ b/e2e/__tests__/dependencyClash.test.ts @@ -14,7 +14,7 @@ import runJest from '../runJest'; const tempDir = path.resolve(tmpdir(), 'clashing-dependencies-test'); const hasteImplModulePath = path .resolve('./packages/jest-haste-map/src/__tests__/haste_impl.js') - .replace(/\\/g, '\\\\'); + .replaceAll('\\', '\\\\'); beforeEach(() => { cleanup(tempDir); diff --git a/e2e/__tests__/failureDetailsProperty.test.ts b/e2e/__tests__/failureDetailsProperty.test.ts index 72fd468ddd2a..3f8d3a2e1b66 100644 --- a/e2e/__tests__/failureDetailsProperty.test.ts +++ b/e2e/__tests__/failureDetailsProperty.test.ts @@ -9,7 +9,7 @@ import {isJestJasmineRun} from '@jest/test-utils'; import runJest from '../runJest'; const removeStackTraces = (stdout: string) => - stdout.replace( + stdout.replaceAll( /at (new Promise \(\)|.+:\d+:\d+\)?)/g, 'at ', ); diff --git a/e2e/__tests__/failures.test.ts b/e2e/__tests__/failures.test.ts index b22a6bd11ad0..3a9dcfcd840f 100644 --- a/e2e/__tests__/failures.test.ts +++ b/e2e/__tests__/failures.test.ts @@ -11,13 +11,13 @@ import runJest from '../runJest'; const dir = path.resolve(__dirname, '../failures'); -const normalizeDots = (text: string) => text.replace(/\.+$/gm, '.'); +const normalizeDots = (text: string) => text.replaceAll(/\.+$/gm, '.'); function cleanStderr(stderr: string) { const {rest} = extractSummary(stderr); return rest - .replace(/.*(jest-jasmine2|jest-circus).*\n/g, '') - .replace(new RegExp('Failed: Object {', 'g'), 'thrown: Object {'); + .replaceAll(/.*(jest-jasmine2|jest-circus).*\n/g, '') + .replaceAll(new RegExp('Failed: Object {', 'g'), 'thrown: Object {'); } beforeAll(() => { @@ -101,7 +101,7 @@ test('works with error with cause thrown outside tests', () => { const summary = normalizeDots(cleanStderr(stderr)); const sanitizedSummary = summary - .replace(/ Suite\.f /g, ' f ') // added by jasmine runner + .replaceAll(' Suite.f ', ' f ') // added by jasmine runner .split('\n') .map(line => line.trim()) // jasmine runner does not come with the same indentation .join('\n'); diff --git a/e2e/__tests__/globals.test.ts b/e2e/__tests__/globals.test.ts index 09b30f4532de..5382e1d517ee 100644 --- a/e2e/__tests__/globals.test.ts +++ b/e2e/__tests__/globals.test.ts @@ -20,7 +20,7 @@ const TEST_DIR = path.resolve(DIR, '__tests__'); function cleanStderr(stderr: string) { const {rest} = extractSummary(stderr); - return rest.replace(/.*(jest-jasmine2).*\n/g, ''); + return rest.replaceAll(/.*(jest-jasmine2).*\n/g, ''); } beforeEach(() => { diff --git a/e2e/__tests__/jest.config.js.test.ts b/e2e/__tests__/jest.config.js.test.ts index dc87668a5341..5743a83d29a0 100644 --- a/e2e/__tests__/jest.config.js.test.ts +++ b/e2e/__tests__/jest.config.js.test.ts @@ -47,7 +47,7 @@ test('traverses directory tree up until it finds jest.config', () => { ); // Snapshot the console.loged `process.cwd()` and make sure it stays the same - expect(stdout.replace(/^\W+(.*)e2e/gm, '<>')).toMatchSnapshot(); + expect(stdout.replaceAll(/^\W+(.*)e2e/gm, '<>')).toMatchSnapshot(); const {rest, summary} = extractSummary(stderr); expect(exitCode).toBe(0); diff --git a/e2e/__tests__/jest.config.ts.test.ts b/e2e/__tests__/jest.config.ts.test.ts index 5e71eb9280ca..f5b316d4878b 100644 --- a/e2e/__tests__/jest.config.ts.test.ts +++ b/e2e/__tests__/jest.config.ts.test.ts @@ -65,7 +65,7 @@ test('traverses directory tree up until it finds jest.config', () => { ); // Snapshot the console.logged `process.cwd()` and make sure it stays the same - expect(stdout.replace(/^\W+(.*)e2e/gm, '<>')).toMatchSnapshot(); + expect(stdout.replaceAll(/^\W+(.*)e2e/gm, '<>')).toMatchSnapshot(); const {rest, summary} = extractSummary(stderr); expect(exitCode).toBe(0); diff --git a/e2e/__tests__/multipleConfigs.ts b/e2e/__tests__/multipleConfigs.ts index e026338e0b05..c0f2dd681ed6 100644 --- a/e2e/__tests__/multipleConfigs.ts +++ b/e2e/__tests__/multipleConfigs.ts @@ -20,7 +20,7 @@ test('multiple configs will throw error', () => { expect(exitCode).toBe(1); expect(stderr).toContain(MULTIPLE_CONFIGS_WARNING_TEXT); - const cleanStdErr = stderr.replace(new RegExp(rootDir, 'g'), ''); + const cleanStdErr = stderr.replaceAll(new RegExp(rootDir, 'g'), ''); expect(cleanStdErr).toMatchSnapshot(); }); diff --git a/e2e/__tests__/showConfig.test.ts b/e2e/__tests__/showConfig.test.ts index a921def3f0ac..621b26fec478 100644 --- a/e2e/__tests__/showConfig.test.ts +++ b/e2e/__tests__/showConfig.test.ts @@ -29,16 +29,16 @@ test('--showConfig outputs config info and exits', () => { ]); stdout = stdout - .replace(/\\\\node_modules\\\\/g, 'node_modules') - .replace(/\\\\\.pnp\\\\\.\[\^[/\\]+]\+\$/g, '<>') - .replace(/\\\\(?:([^.]+?)|$)/g, '/$1') - .replace(/"cacheDirectory": "(.+)"/g, '"cacheDirectory": "/tmp/jest"') - .replace(/"id": "(.+)"/g, '"id": "[md5 hash]"') - .replace(/"version": "(.+)"/g, '"version": "[version]"') - .replace(/"maxWorkers": (\d+)/g, '"maxWorkers": "[maxWorkers]"') - .replace(/"\S*show-config-test/gm, '"<>') - .replace(/"\S*\/jest\/packages/gm, '"<>') - .replace(/"seed": (-?\d+)/g, '"seed": <>'); + .replaceAll('\\\\node_modules\\\\', 'node_modules') + .replaceAll(/\\\\\.pnp\\\\\.\[\^[/\\]+]\+\$/g, '<>') + .replaceAll(/\\\\(?:([^.]+?)|$)/g, '/$1') + .replaceAll(/"cacheDirectory": "(.+)"/g, '"cacheDirectory": "/tmp/jest"') + .replaceAll(/"id": "(.+)"/g, '"id": "[md5 hash]"') + .replaceAll(/"version": "(.+)"/g, '"version": "[version]"') + .replaceAll(/"maxWorkers": (\d+)/g, '"maxWorkers": "[maxWorkers]"') + .replaceAll(/"\S*show-config-test/gm, '"<>') + .replaceAll(/"\S*\/jest\/packages/gm, '"<>') + .replaceAll(/"seed": (-?\d+)/g, '"seed": <>'); expect(stdout).toMatchSnapshot(); }); diff --git a/e2e/__tests__/watchModeUpdateSnapshot.test.ts b/e2e/__tests__/watchModeUpdateSnapshot.test.ts index 72332142fd96..403d7a2aab6b 100644 --- a/e2e/__tests__/watchModeUpdateSnapshot.test.ts +++ b/e2e/__tests__/watchModeUpdateSnapshot.test.ts @@ -17,7 +17,7 @@ beforeEach(() => cleanup(DIR)); afterAll(() => cleanup(DIR)); expect.addSnapshotSerializer({ - print: val => (val as string).replace(/\[s\[u/g, '\n'), + print: val => (val as string).replaceAll('[s', '\n'), test: val => typeof val === 'string' && val.includes('[s'), }); diff --git a/e2e/coverage-handlebars/__tests__/greet.js b/e2e/coverage-handlebars/__tests__/greet.js index 8f7ac711d374..41aa00de1215 100644 --- a/e2e/coverage-handlebars/__tests__/greet.js +++ b/e2e/coverage-handlebars/__tests__/greet.js @@ -7,7 +7,7 @@ const greet = require('../greet.hbs'); test('am', () => { - expect(greet({am: true, name: 'Joe'}).replace(/\r\n/g, '\n')).toBe( + expect(greet({am: true, name: 'Joe'}).replaceAll('\r\n', '\n')).toBe( '

Good\n morning\nJoe!

\n', ); }); diff --git a/packages/expect-utils/src/utils.ts b/packages/expect-utils/src/utils.ts index 6fb9395f987c..4872e4a5c7b5 100644 --- a/packages/expect-utils/src/utils.ts +++ b/packages/expect-utils/src/utils.ts @@ -480,7 +480,7 @@ export const pathAsArray = (propertyPath: string): Array => { properties.push(''); } - propertyPath.replace(pattern, match => { + propertyPath.replaceAll(pattern, match => { properties.push(match); return match; }); diff --git a/packages/expect/src/print.ts b/packages/expect/src/print.ts index 67887ec32e87..b0d363bed491 100644 --- a/packages/expect/src/print.ts +++ b/packages/expect/src/print.ts @@ -18,7 +18,7 @@ import { // Format substring but do not enclose in double quote marks. // The replacement is compatible with pretty-format package. -const printSubstring = (val: string): string => val.replace(/"|\\/g, '\\$&'); +const printSubstring = (val: string): string => val.replaceAll(/"|\\/g, '\\$&'); export const printReceivedStringContainExpectedSubstring = ( received: string, diff --git a/packages/expect/src/spyMatchers.ts b/packages/expect/src/spyMatchers.ts index 4b7efa1e2a7d..eb1c07092ae5 100644 --- a/packages/expect/src/spyMatchers.ts +++ b/packages/expect/src/spyMatchers.ts @@ -216,7 +216,7 @@ const printExpectedReceivedCallsPositive = ( ); }; -const indentation = 'Received'.replace(/\w/g, ' '); +const indentation = 'Received'.replaceAll(/\w/g, ' '); const printDiffCall = ( expected: Array, diff --git a/packages/expect/tsconfig.json b/packages/expect/tsconfig.json index 6e4edc6dc4da..3804c7c3ac38 100644 --- a/packages/expect/tsconfig.json +++ b/packages/expect/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "lib": ["es2020", "es2021.promise", "es2022.error", "dom"], + "lib": ["es2021", "es2022.error", "dom"], "rootDir": "src", "outDir": "build" }, diff --git a/packages/jest-circus/src/__mocks__/testUtils.ts b/packages/jest-circus/src/__mocks__/testUtils.ts index fe903ffb3db6..cca172c8ec6b 100644 --- a/packages/jest-circus/src/__mocks__/testUtils.ts +++ b/packages/jest-circus/src/__mocks__/testUtils.ts @@ -9,15 +9,15 @@ import {sync as spawnSync} from 'execa'; import * as fs from 'graceful-fs'; import tempy = require('tempy'); -const CIRCUS_PATH = require.resolve('../').replace(/\\/g, '\\\\'); -const CIRCUS_RUN_PATH = require.resolve('../run').replace(/\\/g, '\\\\'); -const CIRCUS_STATE_PATH = require.resolve('../state').replace(/\\/g, '\\\\'); +const CIRCUS_PATH = require.resolve('../').replaceAll('\\', '\\\\'); +const CIRCUS_RUN_PATH = require.resolve('../run').replaceAll('\\', '\\\\'); +const CIRCUS_STATE_PATH = require.resolve('../state').replaceAll('\\', '\\\\'); const TEST_EVENT_HANDLER_PATH = require .resolve('./testEventHandler') - .replace(/\\/g, '\\\\'); + .replaceAll('\\', '\\\\'); const BABEL_REGISTER_PATH = require .resolve('@babel/register') - .replace(/\\/g, '\\\\'); + .replaceAll('\\', '\\\\'); export const runTest = ( source: string, diff --git a/packages/jest-circus/src/formatNodeAssertErrors.ts b/packages/jest-circus/src/formatNodeAssertErrors.ts index 0ca301542679..3d617aa78475 100644 --- a/packages/jest-circus/src/formatNodeAssertErrors.ts +++ b/packages/jest-circus/src/formatNodeAssertErrors.ts @@ -135,7 +135,7 @@ function assertionErrorMessage( const operatorName = getOperatorName(operator, stack); const trimmedStack = stack .replace(message, '') - .replace(/AssertionError(.*)/g, ''); + .replaceAll(/AssertionError(.*)/g, ''); if (operatorName === 'doesNotThrow') { return ( diff --git a/packages/jest-config/src/Deprecated.ts b/packages/jest-config/src/Deprecated.ts index 81dd9dc68cd8..c319f13d2be4 100644 --- a/packages/jest-config/src/Deprecated.ts +++ b/packages/jest-config/src/Deprecated.ts @@ -10,7 +10,7 @@ import type {DeprecatedOptions} from 'jest-validate'; function formatDeprecation(message: string): string { const lines = [ - message.replace(/\*(.+?)\*/g, (_, s) => chalk.bold(`"${s}"`)), + message.replaceAll(/\*(.+?)\*/g, (_, s) => chalk.bold(`"${s}"`)), '', 'Please update your configuration.', ]; diff --git a/packages/jest-config/src/normalize.ts b/packages/jest-config/src/normalize.ts index 4d2ebcad3282..b317a0e86691 100644 --- a/packages/jest-config/src/normalize.ts +++ b/packages/jest-config/src/normalize.ts @@ -300,7 +300,7 @@ const normalizeUnmockedModulePathPatterns = ( // For patterns, direct global substitution is far more ideal, so we // special case substitutions for patterns here. options[key]!.map(pattern => - replacePathSepForRegex(pattern.replace(//g, options.rootDir)), + replacePathSepForRegex(pattern.replaceAll('', options.rootDir)), ); const normalizeMissingOptions = ( diff --git a/packages/jest-config/src/utils.ts b/packages/jest-config/src/utils.ts index 51d4ec0fd6fe..78be841f767e 100644 --- a/packages/jest-config/src/utils.ts +++ b/packages/jest-config/src/utils.ts @@ -52,7 +52,7 @@ export const resolve = ( }; export const escapeGlobCharacters = (path: string): string => - path.replace(/([!()*?[\\\]{}])/g, '\\$1'); + path.replaceAll(/([!()*?[\\\]{}])/g, '\\$1'); export const replaceRootDirInPath = ( rootDir: string, diff --git a/packages/jest-console/src/BufferedConsole.ts b/packages/jest-console/src/BufferedConsole.ts index d83bba0fd577..21162ac14289 100644 --- a/packages/jest-console/src/BufferedConsole.ts +++ b/packages/jest-console/src/BufferedConsole.ts @@ -79,7 +79,7 @@ export default class BufferedConsole extends Console { throw error; } // https://github.com/jestjs/jest/pull/13422#issuecomment-1273396392 - this._log('assert', error.toString().replace(/:\n\n.*\n/gs, '')); + this._log('assert', error.toString().replaceAll(/:\n\n.*\n/gs, '')); } } diff --git a/packages/jest-console/src/CustomConsole.ts b/packages/jest-console/src/CustomConsole.ts index 915274d5d774..41457aa7fc77 100644 --- a/packages/jest-console/src/CustomConsole.ts +++ b/packages/jest-console/src/CustomConsole.ts @@ -58,7 +58,7 @@ export default class CustomConsole extends Console { throw error; } // https://github.com/jestjs/jest/pull/13422#issuecomment-1273396392 - this._logError('assert', error.toString().replace(/:\n\n.*\n/gs, '')); + this._logError('assert', error.toString().replaceAll(/:\n\n.*\n/gs, '')); } } diff --git a/packages/jest-core/src/SearchSource.ts b/packages/jest-core/src/SearchSource.ts index 4ea2c9d59a97..db8230b16f9d 100644 --- a/packages/jest-core/src/SearchSource.ts +++ b/packages/jest-core/src/SearchSource.ts @@ -55,7 +55,7 @@ const hasSCM = (changedFilesInfo: ChangedFiles) => { }; function normalizePosix(filePath: string) { - return filePath.replace(/\\/g, '/'); + return filePath.replaceAll('\\', '/'); } export default class SearchSource { diff --git a/packages/jest-docblock/src/index.ts b/packages/jest-docblock/src/index.ts index bbf4fad3b132..08a0aa456a3d 100644 --- a/packages/jest-docblock/src/index.ts +++ b/packages/jest-docblock/src/index.ts @@ -45,26 +45,26 @@ export function parseWithComments(docblock: string): { docblock = docblock .replace(commentStartRe, '') .replace(commentEndRe, '') - .replace(stringStartRe, '$1'); + .replaceAll(stringStartRe, '$1'); // Normalize multi-line directives let prev = ''; while (prev !== docblock) { prev = docblock; - docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`); + docblock = docblock.replaceAll(multilineRe, `${line}$1 $2${line}`); } docblock = docblock.replace(ltrimNewlineRe, '').trimEnd(); const result = Object.create(null) as Pragmas; const comments = docblock - .replace(propertyRe, '') + .replaceAll(propertyRe, '') .replace(ltrimNewlineRe, '') .trimEnd(); let match; while ((match = propertyRe.exec(docblock))) { // strip linecomments from pragmas - const nextPragma = match[2].replace(lineCommentRe, ''); + const nextPragma = match[2].replaceAll(lineCommentRe, ''); if ( typeof result[match[1]] === 'string' || Array.isArray(result[match[1]]) diff --git a/packages/jest-each/src/bind.ts b/packages/jest-each/src/bind.ts index 98e7991f14d9..c6003c881986 100644 --- a/packages/jest-each/src/bind.ts +++ b/packages/jest-each/src/bind.ts @@ -101,7 +101,7 @@ const buildTemplateTests = ( }; const getHeadingKeys = (headings: string): Array => - extractValidTemplateHeadings(headings).replace(/\s/g, '').split('|'); + extractValidTemplateHeadings(headings).replaceAll(/\s/g, '').split('|'); const applyArguments = ( supportsDone: boolean, diff --git a/packages/jest-each/src/table/array.ts b/packages/jest-each/src/table/array.ts index ed30c9eda58f..e411ff9cd9f1 100644 --- a/packages/jest-each/src/table/array.ts +++ b/packages/jest-each/src/table/array.ts @@ -26,7 +26,7 @@ export default function array( if (isTemplates(title, arrayTable)) { return arrayTable.map((template, index) => ({ arguments: [template], - title: interpolateVariables(title, template, index).replace( + title: interpolateVariables(title, template, index).replaceAll( ESCAPED_PLACEHOLDER_PREFIX, PLACEHOLDER_PREFIX, ), @@ -73,11 +73,14 @@ const formatTitle = ( }, interpolateTitleIndex(interpolateEscapedPlaceholders(title), rowIndex), ) - .replace(new RegExp(JEST_EACH_PLACEHOLDER_ESCAPE, 'g'), PLACEHOLDER_PREFIX); + .replaceAll( + new RegExp(JEST_EACH_PLACEHOLDER_ESCAPE, 'g'), + PLACEHOLDER_PREFIX, + ); const normalisePlaceholderValue = (value: unknown) => typeof value === 'string' - ? value.replace( + ? value.replaceAll( new RegExp(PLACEHOLDER_PREFIX, 'g'), JEST_EACH_PLACEHOLDER_ESCAPE, ) @@ -87,7 +90,7 @@ const getMatchingPlaceholders = (title: string) => title.match(SUPPORTED_PLACEHOLDERS) || []; const interpolateEscapedPlaceholders = (title: string) => - title.replace(ESCAPED_PLACEHOLDER_PREFIX, JEST_EACH_PLACEHOLDER_ESCAPE); + title.replaceAll(ESCAPED_PLACEHOLDER_PREFIX, JEST_EACH_PLACEHOLDER_ESCAPE); const interpolateTitleIndex = (title: string, index: number) => title.replace(INDEX_PLACEHOLDER, index.toString()); diff --git a/packages/jest-each/src/table/interpolation.ts b/packages/jest-each/src/table/interpolation.ts index 116ce81dc1a8..194dea97c655 100644 --- a/packages/jest-each/src/table/interpolation.ts +++ b/packages/jest-each/src/table/interpolation.ts @@ -19,7 +19,7 @@ export const interpolateVariables = ( index: number, ): string => title - .replace( + .replaceAll( new RegExp(`\\$(${Object.keys(template).join('|')})[.\\w]*`, 'g'), match => { const keyPath = match.slice(1).split('.'); diff --git a/packages/jest-fake-timers/tsconfig.json b/packages/jest-fake-timers/tsconfig.json index 483142698671..35e2ed77581f 100644 --- a/packages/jest-fake-timers/tsconfig.json +++ b/packages/jest-fake-timers/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "lib": ["es2020", "dom"], + "lib": ["es2021", "dom"], "rootDir": "src", "outDir": "build" }, diff --git a/packages/jest-haste-map/src/__tests__/dependencyExtractor.js b/packages/jest-haste-map/src/__tests__/dependencyExtractor.js index 27b071b0aa90..1e669a39a556 100644 --- a/packages/jest-haste-map/src/__tests__/dependencyExtractor.js +++ b/packages/jest-haste-map/src/__tests__/dependencyExtractor.js @@ -21,9 +21,9 @@ export function extract(code, filePath, defaultDependencyExtractor) { }; code - .replace(blockCommentRe, '') - .replace(lineCommentRe, '') - .replace(LOAD_MODULE_RE, addDependency); + .replaceAll(blockCommentRe, '') + .replaceAll(lineCommentRe, '') + .replaceAll(LOAD_MODULE_RE, addDependency); return dependencies; } diff --git a/packages/jest-haste-map/src/__tests__/get_mock_name.test.js b/packages/jest-haste-map/src/__tests__/get_mock_name.test.js index dc4cd21c1c4c..f786ec588ef2 100644 --- a/packages/jest-haste-map/src/__tests__/get_mock_name.test.js +++ b/packages/jest-haste-map/src/__tests__/get_mock_name.test.js @@ -15,7 +15,7 @@ describe('getMockName', () => { expect(getMockName(path.join('a', '__mocks__', 'c.js'))).toBe('c'); expect(getMockName(path.join('a', '__mocks__', 'c', 'd.js'))).toBe( - path.join('c', 'd').replace(/\\/g, '/'), + path.join('c', 'd').replaceAll('\\', '/'), ); }); }); diff --git a/packages/jest-haste-map/src/__tests__/index.test.js b/packages/jest-haste-map/src/__tests__/index.test.js index 3787dbbd239e..5720b691f7f4 100644 --- a/packages/jest-haste-map/src/__tests__/index.test.js +++ b/packages/jest-haste-map/src/__tests__/index.test.js @@ -45,7 +45,7 @@ jest.mock('../crawlers/watchman', () => ({ for (const file in list) { if ( - new RegExp(roots.join('|').replace(/\\/g, '\\\\')).test(file) && + new RegExp(roots.join('|').replaceAll('\\', '\\\\')).test(file) && !ignore(file) ) { const relativeFilePath = path.relative(rootDir, file); @@ -772,7 +772,7 @@ describe('HasteMap', () => { ).build(); } catch { expect( - console.error.mock.calls[0][0].replace(/\\/g, '/'), + console.error.mock.calls[0][0].replaceAll('\\', '/'), ).toMatchSnapshot(); } }); @@ -790,7 +790,9 @@ describe('HasteMap', () => { // non-determinism later on. expect(data.map.get('Strawberry')[H.GENERIC_PLATFORM]).toBeUndefined(); - expect(console.warn.mock.calls[0][0].replace(/\\/g, '/')).toMatchSnapshot(); + expect( + console.warn.mock.calls[0][0].replaceAll('\\', '/'), + ).toMatchSnapshot(); }); it('warns on duplicate module ids only once', async () => { @@ -1711,7 +1713,7 @@ describe('HasteMap', () => { H.MODULE, }), ); - expect(error.message.replace(/\\/g, '/')).toMatchSnapshot(); + expect(error.message.replaceAll('\\', '/')).toMatchSnapshot(); } } diff --git a/packages/jest-haste-map/src/crawlers/__tests__/node.test.js b/packages/jest-haste-map/src/crawlers/__tests__/node.test.js index babe8b41e5e8..be9bdf2ba68a 100644 --- a/packages/jest-haste-map/src/crawlers/__tests__/node.test.js +++ b/packages/jest-haste-map/src/crawlers/__tests__/node.test.js @@ -115,7 +115,7 @@ jest.mock('graceful-fs', () => { const pearMatcher = path => /pear/.test(path); const normalize = path => - process.platform === 'win32' ? path.replace(/\//g, '\\') : path; + process.platform === 'win32' ? path.replaceAll('/', '\\') : path; const createMap = obj => new Map(Object.keys(obj).map(key => [normalize(key), obj[key]])); diff --git a/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js b/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js index 77c0f5672eff..a78cbd41ef34 100644 --- a/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js +++ b/packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js @@ -33,7 +33,7 @@ jest.mock('fb-watchman', () => { return {Client}; }); -const forcePOSIXPaths = path => path.replace(/\\/g, '/'); +const forcePOSIXPaths = path => path.replaceAll('\\', '/'); const pearMatcher = path => /pear/.test(path); let watchman; diff --git a/packages/jest-haste-map/src/getMockName.ts b/packages/jest-haste-map/src/getMockName.ts index b33573357ed3..b5dde38a280d 100644 --- a/packages/jest-haste-map/src/getMockName.ts +++ b/packages/jest-haste-map/src/getMockName.ts @@ -13,7 +13,7 @@ const getMockName = (filePath: string): string => { const mockPath = filePath.split(MOCKS_PATTERN)[1]; return mockPath .slice(0, mockPath.lastIndexOf(path.extname(mockPath))) - .replace(/\\/g, '/'); + .replaceAll('\\', '/'); }; export default getMockName; diff --git a/packages/jest-haste-map/src/index.ts b/packages/jest-haste-map/src/index.ts index 22bace8a9f22..55d89af56d82 100644 --- a/packages/jest-haste-map/src/index.ts +++ b/packages/jest-haste-map/src/index.ts @@ -346,7 +346,7 @@ class HasteMap extends EventEmitter implements IHasteMap { const hash = createHash('sha1').update(extra.join('')); return path.join( tmpdir, - `${id.replace(/\W/g, '-')}-${hash.digest('hex').slice(0, 32)}`, + `${id.replaceAll(/\W/g, '-')}-${hash.digest('hex').slice(0, 32)}`, ); } diff --git a/packages/jest-haste-map/src/lib/dependencyExtractor.ts b/packages/jest-haste-map/src/lib/dependencyExtractor.ts index bd8a8cc27bb2..0b7fa2ea4bf8 100644 --- a/packages/jest-haste-map/src/lib/dependencyExtractor.ts +++ b/packages/jest-haste-map/src/lib/dependencyExtractor.ts @@ -80,8 +80,8 @@ export const extractor: DependencyExtractor = { }; code - .replace(BLOCK_COMMENT_RE, '') - .replace(LINE_COMMENT_RE, '') + .replaceAll(BLOCK_COMMENT_RE, '') + .replaceAll(LINE_COMMENT_RE, '') .replace(IMPORT_OR_EXPORT_RE, addDependency) .replace(REQUIRE_OR_DYNAMIC_IMPORT_RE, addDependency) .replace(JEST_EXTENSIONS_RE, addDependency); diff --git a/packages/jest-haste-map/src/lib/normalizePathSep.ts b/packages/jest-haste-map/src/lib/normalizePathSep.ts index 5f409429f80f..5ee57cb98e64 100644 --- a/packages/jest-haste-map/src/lib/normalizePathSep.ts +++ b/packages/jest-haste-map/src/lib/normalizePathSep.ts @@ -12,7 +12,7 @@ if (path.sep === '/') { normalizePathSep = (filePath: string): string => filePath; } else { normalizePathSep = (filePath: string): string => - filePath.replace(/\//g, path.sep); + filePath.replaceAll('/', path.sep); } export default normalizePathSep; diff --git a/packages/jest-jasmine2/src/assertionErrorMessage.ts b/packages/jest-jasmine2/src/assertionErrorMessage.ts index 8cf91446f1f6..5251719466f5 100644 --- a/packages/jest-jasmine2/src/assertionErrorMessage.ts +++ b/packages/jest-jasmine2/src/assertionErrorMessage.ts @@ -98,7 +98,7 @@ function assertionErrorMessage( const operatorName = getOperatorName(operator, stack); const trimmedStack = stack .replace(message, '') - .replace(/AssertionError(.*)/g, ''); + .replaceAll(/AssertionError(.*)/g, ''); if (operatorName === 'doesNotThrow') { return `${ diff --git a/packages/jest-matcher-utils/src/index.ts b/packages/jest-matcher-utils/src/index.ts index 2778ea75d7a1..5af1c5872e9e 100644 --- a/packages/jest-matcher-utils/src/index.ts +++ b/packages/jest-matcher-utils/src/index.ts @@ -124,12 +124,12 @@ export const stringify = ( }; export const highlightTrailingWhitespace = (text: string): string => - text.replace(/\s+$/gm, chalk.inverse('$&')); + text.replaceAll(/\s+$/gm, chalk.inverse('$&')); // Instead of inverse highlight which now implies a change, // replace common spaces with middle dot at the end of any line. const replaceTrailingSpaces = (text: string): string => - text.replace(/\s+$/gm, spaces => SPACE_SYMBOL.repeat(spaces.length)); + text.replaceAll(/\s+$/gm, spaces => SPACE_SYMBOL.repeat(spaces.length)); export const printReceived = (object: unknown): string => RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); diff --git a/packages/jest-matcher-utils/tsconfig.json b/packages/jest-matcher-utils/tsconfig.json index e59af10a490f..5a49ad0a0258 100644 --- a/packages/jest-matcher-utils/tsconfig.json +++ b/packages/jest-matcher-utils/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "lib": ["es2020", "dom"], + "lib": ["es2021", "dom"], "rootDir": "src", "outDir": "build" }, diff --git a/packages/jest-message-util/src/index.ts b/packages/jest-message-util/src/index.ts index 5cc67e50ef2a..fd6efbb88e30 100644 --- a/packages/jest-message-util/src/index.ts +++ b/packages/jest-message-util/src/index.ts @@ -65,7 +65,7 @@ const EXEC_ERROR_MESSAGE = 'Test suite failed to run'; const NOT_EMPTY_LINE_REGEXP = /^(?!$)/gm; export const indentAllLines = (lines: string): string => - lines.replace(NOT_EMPTY_LINE_REGEXP, MESSAGE_INDENT); + lines.replaceAll(NOT_EMPTY_LINE_REGEXP, MESSAGE_INDENT); const trim = (string: string) => (string || '').trim(); diff --git a/packages/jest-mock/src/index.ts b/packages/jest-mock/src/index.ts index 6cdfda373841..2edbd578d523 100644 --- a/packages/jest-mock/src/index.ts +++ b/packages/jest-mock/src/index.ts @@ -906,7 +906,7 @@ export class ModuleMocker { // It's also a syntax error to define a function with a reserved character // as part of it's name. if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) { - name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, '$'); + name = name.replaceAll(FUNCTION_NAME_RESERVED_REPLACE, '$'); } const body = diff --git a/packages/jest-regex-util/src/index.ts b/packages/jest-regex-util/src/index.ts index 9aaaf77a58d0..21b55f6ba9dc 100644 --- a/packages/jest-regex-util/src/index.ts +++ b/packages/jest-regex-util/src/index.ts @@ -12,17 +12,17 @@ export const escapePathForRegex = (dir: string): string => { if (sep === '\\') { // Replace "\" with "/" so it's not escaped by escapeStrForRegex. // replacePathSepForRegex will convert it back. - dir = dir.replace(/\\/g, '/'); + dir = dir.replaceAll('\\', '/'); } return replacePathSepForRegex(escapeStrForRegex(dir)); }; export const escapeStrForRegex = (string: string): string => - string.replace(/[$()*+.?[\\\]^{|}]/g, '\\$&'); + string.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&'); export const replacePathSepForRegex = (string: string): string => { if (sep === '\\') { - return string.replace( + return string.replaceAll( /(\/|(.)?\\(?![$()*+.?[\\\]^{|}]))/g, (_match, _, p2) => (p2 && p2 !== '\\' ? `${p2}\\\\` : '\\\\'), ); diff --git a/packages/jest-reporters/src/GitHubActionsReporter.ts b/packages/jest-reporters/src/GitHubActionsReporter.ts index 80e657461a10..d14ab21f78ef 100644 --- a/packages/jest-reporters/src/GitHubActionsReporter.ts +++ b/packages/jest-reporters/src/GitHubActionsReporter.ts @@ -143,7 +143,10 @@ export default class GitHubActionsReporter extends BaseReporter { #createAnnotation({file, line, message, title, type}: AnnotationOptions) { message = stripAnsi( // copied from: https://github.com/actions/toolkit/blob/main/packages/core/src/command.ts - message.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A'), + message + .replaceAll('%', '%25') + .replaceAll('\r', '%0D') + .replaceAll('\n', '%0A'), ); this.log( diff --git a/packages/jest-reporters/src/__tests__/SummaryReporter.test.js b/packages/jest-reporters/src/__tests__/SummaryReporter.test.js index 115e36382e24..53f0f61a22b3 100644 --- a/packages/jest-reporters/src/__tests__/SummaryReporter.test.js +++ b/packages/jest-reporters/src/__tests__/SummaryReporter.test.js @@ -122,7 +122,7 @@ test('snapshots all have results (no update)', () => { requireReporter(); const testReporter = new SummaryReporter(globalConfig); testReporter.onRunComplete(new Set(), aggregatedResults); - expect(results.join('').replace(/\\/g, '/')).toMatchSnapshot(); + expect(results.join('').replaceAll('\\', '/')).toMatchSnapshot(); }); test('snapshots all have results (after update)', () => { @@ -159,7 +159,7 @@ test('snapshots all have results (after update)', () => { requireReporter(); const testReporter = new SummaryReporter(globalConfig); testReporter.onRunComplete(new Set(), aggregatedResults); - expect(results.join('').replace(/\\/g, '/')).toMatchSnapshot(); + expect(results.join('').replaceAll('\\', '/')).toMatchSnapshot(); }); describe('summaryThreshold option', () => { @@ -200,7 +200,7 @@ describe('summaryThreshold option', () => { requireReporter(); const testReporter = new SummaryReporter(globalConfig, options); testReporter.onRunComplete(new Set(), aggregatedResults); - expect(results.join('').replace(/\\/g, '/')).toMatchSnapshot(); + expect(results.join('').replaceAll('\\', '/')).toMatchSnapshot(); }); it('Should not print failure messages when number of test suites is under the threshold', () => { @@ -211,7 +211,7 @@ describe('summaryThreshold option', () => { requireReporter(); const testReporter = new SummaryReporter(globalConfig, options); testReporter.onRunComplete(new Set(), aggregatedResults); - expect(results.join('').replace(/\\/g, '/')).toMatchSnapshot(); + expect(results.join('').replaceAll('\\', '/')).toMatchSnapshot(); }); it('Should not print failure messages when number of test suites is equal to the threshold', () => { @@ -222,7 +222,7 @@ describe('summaryThreshold option', () => { requireReporter(); const testReporter = new SummaryReporter(globalConfig, options); testReporter.onRunComplete(new Set(), aggregatedResults); - expect(results.join('').replace(/\\/g, '/')).toMatchSnapshot(); + expect(results.join('').replaceAll('\\', '/')).toMatchSnapshot(); }); it('Should throw error if threshold is not a number', () => { diff --git a/packages/jest-reporters/src/__tests__/getSnapshotSummary.test.js b/packages/jest-reporters/src/__tests__/getSnapshotSummary.test.js index 70c00b0e9e4c..ff29beefbd56 100644 --- a/packages/jest-reporters/src/__tests__/getSnapshotSummary.test.js +++ b/packages/jest-reporters/src/__tests__/getSnapshotSummary.test.js @@ -40,7 +40,7 @@ test('creates a snapshot summary', () => { expect( getSnapshotSummary(snapshots, globalConfig, UPDATE_COMMAND) .join('\n') - .replace(/\\/g, '/'), + .replaceAll('\\', '/'), ).toMatchSnapshot(); }); @@ -67,7 +67,7 @@ test('creates a snapshot summary after an update', () => { expect( getSnapshotSummary(snapshots, globalConfig, UPDATE_COMMAND) .join('\n') - .replace(/\\/g, '/'), + .replaceAll('\\', '/'), ).toMatchSnapshot(); }); @@ -98,7 +98,7 @@ it('creates a snapshot summary with multiple snapshot being written/updated', () expect( getSnapshotSummary(snapshots, globalConfig, UPDATE_COMMAND) .join('\n') - .replace(/\\/g, '/'), + .replaceAll('\\', '/'), ).toMatchSnapshot(); }); diff --git a/packages/jest-resolve/src/resolver.ts b/packages/jest-resolve/src/resolver.ts index 4efcf3aaa9c2..32bb4d8cd9f9 100644 --- a/packages/jest-resolve/src/resolver.ts +++ b/packages/jest-resolve/src/resolver.ts @@ -435,7 +435,7 @@ export default class Resolver { private _getMapModuleName(matches: RegExpMatchArray | null) { return matches ? (moduleName: string) => - moduleName.replace( + moduleName.replaceAll( /\$(\d+)/g, (_, index) => matches[Number.parseInt(index, 10)] || '', ) diff --git a/packages/jest-snapshot/src/utils.ts b/packages/jest-snapshot/src/utils.ts index 4ee0255f4a2c..817a7ef52995 100644 --- a/packages/jest-snapshot/src/utils.ts +++ b/packages/jest-snapshot/src/utils.ts @@ -192,10 +192,10 @@ export const minify = (val: unknown): string => // Remove double quote marks and unescape double quotes and backslashes. export const deserializeString = (stringified: string): string => - stringified.slice(1, -1).replace(/\\("|\\)/g, '$1'); + stringified.slice(1, -1).replaceAll(/\\("|\\)/g, '$1'); export const escapeBacktickString = (str: string): string => - str.replace(/`|\\|\${/g, '\\$&'); + str.replaceAll(/`|\\|\${/g, '\\$&'); const printBacktickString = (str: string): string => `\`${escapeBacktickString(str)}\``; @@ -206,7 +206,8 @@ export const ensureDirectoryExists = (filePath: string): void => { } catch {} }; -const normalizeNewlines = (string: string) => string.replace(/\r\n|\r/g, '\n'); +const normalizeNewlines = (string: string) => + string.replaceAll(/\r\n|\r/g, '\n'); export const saveSnapshotFile = ( snapshotData: SnapshotData, diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index 3340521c0c7b..e2c3e4f29aa6 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -224,7 +224,7 @@ class ScriptTransformer { const cacheDir = path.join(baseCacheDir, cacheKey[0] + cacheKey[1]); const cacheFilenamePrefix = path .basename(filename, path.extname(filename)) - .replace(/\W/g, ''); + .replaceAll(/\W/g, ''); return slash(path.join(cacheDir, `${cacheFilenamePrefix}_${cacheKey}`)); } diff --git a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts index 1222353730a3..65483fceb8ee 100644 --- a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts +++ b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts @@ -477,7 +477,7 @@ describe('ScriptTransformer', () => { TransformedSource, string, ]): Promise => { - const processorName = `passthrough-preprocessor${filePath.replace( + const processorName = `passthrough-preprocessor${filePath.replaceAll( /\.|\//g, '-', )}`; diff --git a/packages/jest-util/src/replacePathSepForGlob.ts b/packages/jest-util/src/replacePathSepForGlob.ts index aaa13199209d..92449895ad8c 100644 --- a/packages/jest-util/src/replacePathSepForGlob.ts +++ b/packages/jest-util/src/replacePathSepForGlob.ts @@ -6,5 +6,5 @@ */ export default function replacePathSepForGlob(path: string): string { - return path.replace(/\\(?![$()+.?^{}])/g, '/'); + return path.replaceAll(/\\(?![$()+.?^{}])/g, '/'); } diff --git a/packages/jest-validate/src/__tests__/__fixtures__/jestConfig.ts b/packages/jest-validate/src/__tests__/__fixtures__/jestConfig.ts index 8fd81bd7af35..67582d930575 100644 --- a/packages/jest-validate/src/__tests__/__fixtures__/jestConfig.ts +++ b/packages/jest-validate/src/__tests__/__fixtures__/jestConfig.ts @@ -12,7 +12,7 @@ import chalk = require('chalk'); const NODE_MODULES = `${path.sep}node_modules${path.sep}`; const replacePathSepForRegex = (string: string) => { if (path.sep === '\\') { - return string.replace(/(\/|\\(?!\.))/g, '\\\\'); + return string.replaceAll(/(\/|\\(?!\.))/g, '\\\\'); } return string; }; diff --git a/packages/jest-watcher/src/lib/formatTestNameByPattern.ts b/packages/jest-watcher/src/lib/formatTestNameByPattern.ts index 7a60973052ff..ee2e269fbfd7 100644 --- a/packages/jest-watcher/src/lib/formatTestNameByPattern.ts +++ b/packages/jest-watcher/src/lib/formatTestNameByPattern.ts @@ -16,7 +16,7 @@ export default function formatTestNameByPattern( pattern: string, width: number, ): string { - const inlineTestName = testName.replace(/(\r\n|\n|\r)/gm, ENTER); + const inlineTestName = testName.replaceAll(/(\r\n|\n|\r)/gm, ENTER); let regexp; diff --git a/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts b/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts index c3cca40f228c..cab0cc29cba8 100644 --- a/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts +++ b/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts @@ -249,12 +249,12 @@ describe('indent option', () => { // Tests assume that no strings in val contain multiple adjacent spaces! test('non-default: 0 spaces', () => { expect(prettyFormat(val, {...options, indent: 0})).toEqual( - result.replace(/ {2}/g, ''), + result.replaceAll(/ {2}/g, ''), ); }); test('non-default: 4 spaces', () => { expect(prettyFormat(val, {...options, indent: 4})).toEqual( - result.replace(/ {2}/g, ' '.repeat(4)), + result.replaceAll(/ {2}/g, ' '.repeat(4)), ); }); }); diff --git a/packages/pretty-format/src/__tests__/Immutable.test.ts b/packages/pretty-format/src/__tests__/Immutable.test.ts index b2a6f708dec2..bc387cfbf9f7 100644 --- a/packages/pretty-format/src/__tests__/Immutable.test.ts +++ b/packages/pretty-format/src/__tests__/Immutable.test.ts @@ -748,15 +748,21 @@ describe('indent option', () => { // Tests assume that no strings in val contain multiple adjacent spaces! test('non-default: 0 spaces', () => { const indent = 0; - expect(val).toPrettyPrintTo(expected.replace(/ {2}/g, ' '.repeat(indent)), { - indent, - }); + expect(val).toPrettyPrintTo( + expected.replaceAll(/ {2}/g, ' '.repeat(indent)), + { + indent, + }, + ); }); test('non-default: 4 spaces', () => { const indent = 4; - expect(val).toPrettyPrintTo(expected.replace(/ {2}/g, ' '.repeat(indent)), { - indent, - }); + expect(val).toPrettyPrintTo( + expected.replaceAll(/ {2}/g, ' '.repeat(indent)), + { + indent, + }, + ); }); }); diff --git a/packages/pretty-format/src/__tests__/prettyFormat.test.ts b/packages/pretty-format/src/__tests__/prettyFormat.test.ts index cdc8bd23b4cd..22f9119341ee 100644 --- a/packages/pretty-format/src/__tests__/prettyFormat.test.ts +++ b/packages/pretty-format/src/__tests__/prettyFormat.test.ts @@ -539,13 +539,13 @@ describe('prettyFormat()', () => { test('non-default: 0 spaces', () => { const indent = 0; expect(prettyFormat(val, {indent})).toEqual( - expected.replace(/ {2}/g, ' '.repeat(indent)), + expected.replaceAll(/ {2}/g, ' '.repeat(indent)), ); }); test('non-default: 4 spaces', () => { const indent = 4; expect(prettyFormat(val, {indent})).toEqual( - expected.replace(/ {2}/g, ' '.repeat(indent)), + expected.replaceAll(/ {2}/g, ' '.repeat(indent)), ); }); }); diff --git a/packages/pretty-format/src/__tests__/react.test.tsx b/packages/pretty-format/src/__tests__/react.test.tsx index 3e2efa33023f..ef1e85ebbdaa 100644 --- a/packages/pretty-format/src/__tests__/react.test.tsx +++ b/packages/pretty-format/src/__tests__/react.test.tsx @@ -446,13 +446,13 @@ describe('indent option', () => { // Tests assume that no strings in val contain multiple adjacent spaces! test('non-default: 0 spaces', () => { const indent = 0; - assertPrintedJSX(val, expected.replace(/ {2}/g, ' '.repeat(indent)), { + assertPrintedJSX(val, expected.replaceAll(/ {2}/g, ' '.repeat(indent)), { indent, }); }); test('non-default: 4 spaces', () => { const indent = 4; - assertPrintedJSX(val, expected.replace(/ {2}/g, ' '.repeat(indent)), { + assertPrintedJSX(val, expected.replaceAll(/ {2}/g, ' '.repeat(indent)), { indent, }); }); diff --git a/packages/pretty-format/src/index.ts b/packages/pretty-format/src/index.ts index a391008b6ac8..b33c520a5432 100644 --- a/packages/pretty-format/src/index.ts +++ b/packages/pretty-format/src/index.ts @@ -146,7 +146,7 @@ function printBasicValue( } if (typeOf === 'string') { if (escapeString) { - return `"${val.replace(/"|\\/g, '\\$&')}"`; + return `"${val.replaceAll(/"|\\/g, '\\$&')}"`; } return `"${val}"`; } @@ -183,7 +183,7 @@ function printBasicValue( if (toStringed === '[object RegExp]') { if (escapeRegex) { // https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js - return regExpToString.call(val).replace(/[$()*+.?[\\\]^{|}]/g, '\\$&'); + return regExpToString.call(val).replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&'); } return regExpToString.call(val); } @@ -320,7 +320,7 @@ function printPlugin( const indentationNext = indentation + config.indent; return ( indentationNext + - str.replace(NEWLINE_REGEXP, `\n${indentationNext}`) + str.replaceAll(NEWLINE_REGEXP, `\n${indentationNext}`) ); }, { diff --git a/packages/pretty-format/src/plugins/lib/escapeHTML.ts b/packages/pretty-format/src/plugins/lib/escapeHTML.ts index 4122dfea3d48..17520b74d890 100644 --- a/packages/pretty-format/src/plugins/lib/escapeHTML.ts +++ b/packages/pretty-format/src/plugins/lib/escapeHTML.ts @@ -6,5 +6,5 @@ */ export default function escapeHTML(str: string): string { - return str.replace(//g, '>'); + return str.replaceAll('<', '<').replaceAll('>', '>'); } diff --git a/packages/pretty-format/tsconfig.json b/packages/pretty-format/tsconfig.json index 32872475768e..6962ce29124b 100644 --- a/packages/pretty-format/tsconfig.json +++ b/packages/pretty-format/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "lib": ["es2020", "dom"], + "lib": ["es2021", "dom"], "rootDir": "src", "outDir": "build" }, diff --git a/packages/test-utils/src/normalizeIcons.ts b/packages/test-utils/src/normalizeIcons.ts index 6c672384d642..b41ad3088342 100644 --- a/packages/test-utils/src/normalizeIcons.ts +++ b/packages/test-utils/src/normalizeIcons.ts @@ -12,6 +12,6 @@ export function normalizeIcons(str: string): string { // Make sure to keep in sync with `jest-util/src/specialChars` return str - .replace(new RegExp('\u00D7', 'gu'), '\u2715') - .replace(new RegExp('\u221A', 'gu'), '\u2713'); + .replaceAll(new RegExp('\u00D7', 'gu'), '\u2715') + .replaceAll(new RegExp('\u221A', 'gu'), '\u2713'); } diff --git a/scripts/bundleTs.mjs b/scripts/bundleTs.mjs index aab0c79b1e5a..f506d4a08507 100644 --- a/scripts/bundleTs.mjs +++ b/scripts/bundleTs.mjs @@ -195,7 +195,7 @@ await Promise.all( }), ); - definitionFile = definitionFile.replace(/\r\n/g, '\n'); + definitionFile = definitionFile.replaceAll('\r\n', '\n'); const hasNodeTypesReference = definitionFile.includes( typesNodeReferenceDirective,