Skip to content

Commit

Permalink
chore: use String.replaceAll if possible (jestjs#14823)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Dec 31, 2023
1 parent 5736ae3 commit c13bca3
Show file tree
Hide file tree
Showing 68 changed files with 141 additions and 129 deletions.
3 changes: 0 additions & 3 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 6 additions & 6 deletions e2e/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export const linkJestPackage = (packageName: string, cwd: string) => {
export const makeTemplate =
(str: string): ((values?: Array<string>) => 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.');
}
Expand Down Expand Up @@ -191,12 +191,12 @@ export const copyDir = (src: string, dest: string) => {
};

export const replaceSeed = (str: string) =>
str.replace(/Seed: {8}(-?\d+)/g, 'Seed: <<REPLACED>>');
str.replaceAll(/Seed: {8}(-?\d+)/g, 'Seed: <<REPLACED>>');

export const replaceTime = (str: string) =>
str
.replace(/\d*\.?\d+ m?s\b/g, '<<REPLACED>>')
.replace(/, estimated <<REPLACED>>/g, '');
.replaceAll(/\d*\.?\d+ m?s\b/g, '<<REPLACED>>')
.replaceAll(', estimated <<REPLACED>>', '');

// Since Jest does not guarantee the order of tests we'll sort the output.
export const sortLines = (output: string) =>
Expand Down Expand Up @@ -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,
);
Expand All @@ -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(),
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/beforeAllFiltered.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/beforeEachQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
2 changes: 1 addition & 1 deletion e2e/__tests__/customEsmTestSequencers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
10 changes: 5 additions & 5 deletions e2e/__tests__/customTestSequencers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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',
Expand All @@ -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']);
});
Expand All @@ -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',
Expand All @@ -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',
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/declarationErrors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
'',
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/dependencyClash.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/failureDetailsProperty.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 \(<anonymous>\)|.+:\d+:\d+\)?)/g,
'at <stacktrace>',
);
Expand Down
8 changes: 4 additions & 4 deletions e2e/__tests__/failures.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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');
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/globals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/jest.config.js.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, '<<REPLACED>>')).toMatchSnapshot();
expect(stdout.replaceAll(/^\W+(.*)e2e/gm, '<<REPLACED>>')).toMatchSnapshot();

const {rest, summary} = extractSummary(stderr);
expect(exitCode).toBe(0);
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/jest.config.ts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, '<<REPLACED>>')).toMatchSnapshot();
expect(stdout.replaceAll(/^\W+(.*)e2e/gm, '<<REPLACED>>')).toMatchSnapshot();

const {rest, summary} = extractSummary(stderr);
expect(exitCode).toBe(0);
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/multipleConfigs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'), '<rootDir>');
const cleanStdErr = stderr.replaceAll(new RegExp(rootDir, 'g'), '<rootDir>');
expect(cleanStdErr).toMatchSnapshot();
});

Expand Down
20 changes: 10 additions & 10 deletions e2e/__tests__/showConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,16 @@ test('--showConfig outputs config info and exits', () => {
]);

stdout = stdout
.replace(/\\\\node_modules\\\\/g, 'node_modules')
.replace(/\\\\\.pnp\\\\\.\[\^[/\\]+]\+\$/g, '<<REPLACED_PNP_PATH>>')
.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, '"<<REPLACED_ROOT_DIR>>')
.replace(/"\S*\/jest\/packages/gm, '"<<REPLACED_JEST_PACKAGES_DIR>>')
.replace(/"seed": (-?\d+)/g, '"seed": <<RANDOM_SEED>>');
.replaceAll('\\\\node_modules\\\\', 'node_modules')
.replaceAll(/\\\\\.pnp\\\\\.\[\^[/\\]+]\+\$/g, '<<REPLACED_PNP_PATH>>')
.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, '"<<REPLACED_ROOT_DIR>>')
.replaceAll(/"\S*\/jest\/packages/gm, '"<<REPLACED_JEST_PACKAGES_DIR>>')
.replaceAll(/"seed": (-?\d+)/g, '"seed": <<RANDOM_SEED>>');

expect(stdout).toMatchSnapshot();
});
2 changes: 1 addition & 1 deletion e2e/__tests__/watchModeUpdateSnapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[u', '\n'),
test: val => typeof val === 'string' && val.includes('[s'),
});

Expand Down
2 changes: 1 addition & 1 deletion e2e/coverage-handlebars/__tests__/greet.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
'<p>Good\n morning\nJoe!</p>\n',
);
});
2 changes: 1 addition & 1 deletion packages/expect-utils/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ export const pathAsArray = (propertyPath: string): Array<any> => {
properties.push('');
}

propertyPath.replace(pattern, match => {
propertyPath.replaceAll(pattern, match => {
properties.push(match);
return match;
});
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/src/print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/src/spyMatchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ const printExpectedReceivedCallsPositive = (
);
};

const indentation = 'Received'.replace(/\w/g, ' ');
const indentation = 'Received'.replaceAll(/\w/g, ' ');

const printDiffCall = (
expected: Array<unknown>,
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"lib": ["es2020", "es2021.promise", "es2022.error", "dom"],
"lib": ["es2021", "es2022.error", "dom"],
"rootDir": "src",
"outDir": "build"
},
Expand Down
10 changes: 5 additions & 5 deletions packages/jest-circus/src/__mocks__/testUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-circus/src/formatNodeAssertErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-config/src/Deprecated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
];
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-config/src/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(/<rootDir>/g, options.rootDir)),
replacePathSepForRegex(pattern.replaceAll('<rootDir>', options.rootDir)),
);

const normalizeMissingOptions = (
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-config/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-console/src/BufferedConsole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, ''));
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-console/src/CustomConsole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, ''));
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-core/src/SearchSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const hasSCM = (changedFilesInfo: ChangedFiles) => {
};

function normalizePosix(filePath: string) {
return filePath.replace(/\\/g, '/');
return filePath.replaceAll('\\', '/');
}

export default class SearchSource {
Expand Down
Loading

0 comments on commit c13bca3

Please sign in to comment.