chore: enable lint rule for better `RegExp`es (#14803)

This commit is contained in:
Simen Bekkhus 2023-12-29 10:23:18 +01:00 committed by GitHub
parent 5a21906d51
commit eaea490134
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 60 additions and 74 deletions

View File

@ -681,7 +681,6 @@ module.exports = {
'unicorn/prefer-reflect-apply': 'off', 'unicorn/prefer-reflect-apply': 'off',
// TODO: turn on at some point // TODO: turn on at some point
'unicorn/better-regex': 'off',
'unicorn/catch-error-name': 'off', 'unicorn/catch-error-name': 'off',
'unicorn/consistent-function-scoping': 'off', 'unicorn/consistent-function-scoping': 'off',
'unicorn/error-message': 'off', 'unicorn/error-message': 'off',
@ -713,7 +712,6 @@ module.exports = {
'unicorn/prefer-number-properties': 'off', 'unicorn/prefer-number-properties': 'off',
'unicorn/prefer-object-from-entries': 'off', 'unicorn/prefer-object-from-entries': 'off',
'unicorn/prefer-prototype-methods': 'off', 'unicorn/prefer-prototype-methods': 'off',
'unicorn/prefer-regexp-test': 'off',
'unicorn/prefer-spread': 'off', 'unicorn/prefer-spread': 'off',
'unicorn/prefer-string-replace-all': 'off', 'unicorn/prefer-string-replace-all': 'off',
'unicorn/prevent-abbreviations': 'off', 'unicorn/prevent-abbreviations': 'off',

View File

@ -235,7 +235,7 @@ export const createEmptyPackage = (
export const extractSummary = (stdout: string) => { export const extractSummary = (stdout: string) => {
const match = stdout const match = stdout
.replace(/(?:\\[rn])+/g, '\n') .replace(/(?:\\[nr])+/g, '\n')
.match( .match(
/(Seed:.*\n)?Test Suites:.*\nTests.*\nSnapshots.*\nTime.*(\nRan all test suites)*.*\n*$/gm, /(Seed:.*\n)?Test Suites:.*\nTests.*\nSnapshots.*\nTime.*(\nRan all test suites)*.*\n*$/gm,
); );

View File

@ -11,7 +11,7 @@ import runJest from '../runJest';
const dir = path.resolve(__dirname, '../failures'); const dir = path.resolve(__dirname, '../failures');
const normalizeDots = (text: string) => text.replace(/\.{1,}$/gm, '.'); const normalizeDots = (text: string) => text.replace(/\.+$/gm, '.');
function cleanStderr(stderr: string) { function cleanStderr(stderr: string) {
const {rest} = extractSummary(stderr); const {rest} = extractSummary(stderr);
@ -65,7 +65,7 @@ test('works with async failures', () => {
const result = normalizeDots(rest) const result = normalizeDots(rest)
.replace(/.*thrown:.*\n/, '') .replace(/.*thrown:.*\n/, '')
.replace( .replace(
/.*Add a timeout value to this test to increase the timeout, if this is a long-running test. See https:\/\/jestjs.io\/docs\/api#testname-fn-timeout..*/, /.*Add a timeout value to this test to increase the timeout, if this is a long-running test. See https:\/\/jestjs.io\/docs\/api#testname-fn-timeout.+/,
'<REPLACED>', '<REPLACED>',
) )
.replace(/.*Timeout - Async callback was not.*/, '<REPLACED>'); .replace(/.*Timeout - Async callback was not.*/, '<REPLACED>');

View File

@ -115,7 +115,7 @@ describe('async jasmine', () => {
expect(json.numPendingTests).toBe(1); expect(json.numPendingTests).toBe(1);
expect(json.testResults[0].message).toMatch(/concurrent test fails/); expect(json.testResults[0].message).toMatch(/concurrent test fails/);
if (!isJestJasmineRun()) { if (!isJestJasmineRun()) {
expect(stderr.match(/\[\[\w+\]\]/g)).toEqual([ expect(stderr.match(/\[\[\w+]]/g)).toEqual([
'[[beforeAll]]', '[[beforeAll]]',
'[[test]]', '[[test]]',
'[[test]]', '[[test]]',

View File

@ -12,10 +12,10 @@ const dir = resolve(__dirname, '..', 'run-programmatically');
test('run Jest programmatically cjs', () => { test('run Jest programmatically cjs', () => {
const {stdout} = run('node cjs.js --version', dir); const {stdout} = run('node cjs.js --version', dir);
expect(stdout).toMatch(/\d{2}\.\d{1,2}\.\d{1,2}[-\S]*-dev$/); expect(stdout).toMatch(/\d{2}(?:\.\d{1,2}){2}\S*-dev$/);
}); });
test('run Jest programmatically esm', () => { test('run Jest programmatically esm', () => {
const {stdout} = run('node index.js --version', dir); const {stdout} = run('node index.js --version', dir);
expect(stdout).toMatch(/\d{2}\.\d{1,2}\.\d{1,2}[-\S]*-dev$/); expect(stdout).toMatch(/\d{2}(?:\.\d{1,2}){2}\S*-dev$/);
}); });

View File

@ -30,7 +30,7 @@ test('--showConfig outputs config info and exits', () => {
stdout = stdout stdout = stdout
.replace(/\\\\node_modules\\\\/g, 'node_modules') .replace(/\\\\node_modules\\\\/g, 'node_modules')
.replace(/\\\\\.pnp\\\\\.\[\^[/\\]+\]\+\$/g, '<<REPLACED_PNP_PATH>>') .replace(/\\\\\.pnp\\\\\.\[\^[/\\]+]\+\$/g, '<<REPLACED_PNP_PATH>>')
.replace(/\\\\(?:([^.]+?)|$)/g, '/$1') .replace(/\\\\(?:([^.]+?)|$)/g, '/$1')
.replace(/"cacheDirectory": "(.+)"/g, '"cacheDirectory": "/tmp/jest"') .replace(/"cacheDirectory": "(.+)"/g, '"cacheDirectory": "/tmp/jest"')
.replace(/"id": "(.+)"/g, '"id": "[md5 hash]"') .replace(/"id": "(.+)"/g, '"id": "[md5 hash]"')

View File

@ -19,9 +19,7 @@ describe('Stack Trace', () => {
/ReferenceError: thisIsARuntimeError is not defined/, /ReferenceError: thisIsARuntimeError is not defined/,
); );
expect(stderr).toMatch(/> 10 \| thisIsARuntimeError\(\);/); expect(stderr).toMatch(/> 10 \| thisIsARuntimeError\(\);/);
expect(stderr).toMatch( expect(stderr).toMatch(/\s+at\s.+?\s\(__tests__\/runtimeError.test\.js/);
/\s+at\s(?:.+?)\s\(__tests__\/runtimeError.test\.js/,
);
}); });
it('does not print a stack trace for runtime errors when --noStackTrace is given', () => { it('does not print a stack trace for runtime errors when --noStackTrace is given', () => {
@ -37,7 +35,7 @@ describe('Stack Trace', () => {
/ReferenceError: thisIsARuntimeError is not defined/, /ReferenceError: thisIsARuntimeError is not defined/,
); );
expect(stderr).not.toMatch( expect(stderr).not.toMatch(
/\s+at\s(?:.+?)\s\(__tests__\/runtimeError.test\.js/, /\s+at\s.+?\s\(__tests__\/runtimeError.test\.js/,
); );
}); });
@ -47,7 +45,7 @@ describe('Stack Trace', () => {
expect(extractSummary(stderr).summary).toMatchSnapshot(); expect(extractSummary(stderr).summary).toMatchSnapshot();
expect(exitCode).toBe(1); expect(exitCode).toBe(1);
expect(stderr).toMatch(/\s+at\s(?:.+?)\s\(__tests__\/stackTrace.test\.js/); expect(stderr).toMatch(/\s+at\s.+?\s\(__tests__\/stackTrace.test\.js/);
}); });
it('does not print a stack trace for matching errors when --noStackTrace is given', () => { it('does not print a stack trace for matching errors when --noStackTrace is given', () => {
@ -59,9 +57,7 @@ describe('Stack Trace', () => {
expect(extractSummary(stderr).summary).toMatchSnapshot(); expect(extractSummary(stderr).summary).toMatchSnapshot();
expect(exitCode).toBe(1); expect(exitCode).toBe(1);
expect(stderr).not.toMatch( expect(stderr).not.toMatch(/\s+at\s.+?\s\(__tests__\/stackTrace.test\.js/);
/\s+at\s(?:.+?)\s\(__tests__\/stackTrace.test\.js/,
);
}); });
it('prints a stack trace for errors', () => { it('prints a stack trace for errors', () => {
@ -73,16 +69,14 @@ describe('Stack Trace', () => {
expect(stderr).toMatch(/this is unexpected\./); expect(stderr).toMatch(/this is unexpected\./);
expect(stderr).toMatch(/this is a string\./); expect(stderr).toMatch(/this is a string\./);
expect(stderr).toMatch(/\s+at\s(?:.+?)\s\(__tests__\/testError.test\.js/); expect(stderr).toMatch(/\s+at\s.+?\s\(__tests__\/testError.test\.js/);
// Make sure we show Jest's jest-resolve as part of the stack trace // Make sure we show Jest's jest-resolve as part of the stack trace
expect(stderr).toMatch( expect(stderr).toMatch(
/Cannot find module 'this-module-does-not-exist' from '__tests__\/testError\.test\.js'/, /Cannot find module 'this-module-does-not-exist' from '__tests__\/testError\.test\.js'/,
); );
expect(stderr).toMatch( expect(stderr).toMatch(/\s+at\s.+?\s\(.+?jest-resolve\/build\/index\.js/);
/\s+at\s(?:.+?)\s\((?:.+?)jest-resolve\/build\/index\.js/,
);
}); });
it('prints a stack trace for errors without message in stack trace', () => { it('prints a stack trace for errors without message in stack trace', () => {
@ -95,7 +89,7 @@ describe('Stack Trace', () => {
expect(stderr).toMatch(/important message/); expect(stderr).toMatch(/important message/);
expect(stderr).toMatch( expect(stderr).toMatch(
/\s+at\s(?:.+?)\s\(__tests__\/stackTraceWithoutMessage.test\.js/, /\s+at\s.+?\s\(__tests__\/stackTraceWithoutMessage.test\.js/,
); );
}); });
@ -108,8 +102,6 @@ describe('Stack Trace', () => {
expect(extractSummary(stderr).summary).toMatchSnapshot(); expect(extractSummary(stderr).summary).toMatchSnapshot();
expect(exitCode).toBe(1); expect(exitCode).toBe(1);
expect(stderr).not.toMatch( expect(stderr).not.toMatch(/\s+at\s.+?\s\(__tests__\/testError.test\.js/);
/\s+at\s(?:.+?)\s\(__tests__\/testError.test\.js/,
);
}); });
}); });

View File

@ -22,7 +22,7 @@ test('works with jest.config.js', () => {
}); });
const {exitCode, stdout, stderr} = runJest(DIR, ['--version']); const {exitCode, stdout, stderr} = runJest(DIR, ['--version']);
expect(stdout).toMatch(/\d{2}\.\d{1,2}\.\d{1,2}[-\S]*-dev$/); expect(stdout).toMatch(/\d{2}(?:\.\d{1,2}){2}\S*-dev$/);
// Only version gets printed and nothing else // Only version gets printed and nothing else
expect(stdout.split(/\n/)).toHaveLength(1); expect(stdout.split(/\n/)).toHaveLength(1);
expect(stderr).toBe(''); expect(stderr).toBe('');

View File

@ -6,7 +6,7 @@
*/ */
'use strict'; 'use strict';
const regex = /\dd \s+ \w \\\[ \. blahzz.* [xyz]+/; const regex = /\dd \s+ \w \\\[ \. blahzz.* [x-z]+/;
test('escape regex', () => expect(regex).toMatchSnapshot()); test('escape regex', () => expect(regex).toMatchSnapshot());

View File

@ -503,7 +503,7 @@ export function emptyObject(obj: unknown): boolean {
return obj && typeof obj === 'object' ? Object.keys(obj).length === 0 : false; return obj && typeof obj === 'object' ? Object.keys(obj).length === 0 : false;
} }
const MULTILINE_REGEXP = /[\r\n]/; const MULTILINE_REGEXP = /[\n\r]/;
export const isOneline = (expected: unknown, received: unknown): boolean => export const isOneline = (expected: unknown, received: unknown): boolean =>
typeof expected === 'string' && typeof expected === 'string' &&

View File

@ -244,7 +244,7 @@ Received message: <r>"apple"</>
exports[`toThrow regexp threw, but message did not match (non-error falsey) 1`] = ` exports[`toThrow regexp threw, but message did not match (non-error falsey) 1`] = `
<d>expect(</><r>received</><d>).</>toThrow<d>(</><g>expected</><d>)</> <d>expect(</><r>received</><d>).</>toThrow<d>(</><g>expected</><d>)</>
Expected pattern: <g>/^[123456789]\\d*/</> Expected pattern: <g>/^[1-9]\\d*/</>
Received value: <r>0</> Received value: <r>0</>
`; `;
@ -261,7 +261,7 @@ Received message: <r>"Invalid<i> array </i>length"</>
exports[`toThrow regexp threw, but message should not match (non-error truthy) 1`] = ` exports[`toThrow regexp threw, but message should not match (non-error truthy) 1`] = `
<d>expect(</><r>received</><d>).</>not<d>.</>toThrow<d>(</><g>expected</><d>)</> <d>expect(</><r>received</><d>).</>not<d>.</>toThrow<d>(</><g>expected</><d>)</>
Expected pattern: not <g>/^[123456789]\\d*/</> Expected pattern: not <g>/^[1-9]\\d*/</>
Received value: <r>404</> Received value: <r>404</>
`; `;

View File

@ -1817,7 +1817,7 @@ describe('.toMatch()', () => {
}); });
it('does not maintain RegExp state between calls', () => { it('does not maintain RegExp state between calls', () => {
const regex = /[f]\d+/gi; const regex = /f\d+/gi;
jestExpect('f123').toMatch(regex); jestExpect('f123').toMatch(regex);
jestExpect('F456').toMatch(regex); jestExpect('F456').toMatch(regex);
jestExpect(regex.lastIndex).toBe(0); jestExpect(regex.lastIndex).toBe(0);

View File

@ -121,7 +121,7 @@ describe('toThrow', () => {
jestExpect(() => { jestExpect(() => {
// eslint-disable-next-line no-throw-literal // eslint-disable-next-line no-throw-literal
throw 0; throw 0;
}).toThrow(/^[123456789]\d*/); }).toThrow(/^[1-9]\d*/);
}).toThrowErrorMatchingSnapshot(); }).toThrowErrorMatchingSnapshot();
}); });
@ -138,7 +138,7 @@ describe('toThrow', () => {
jestExpect(() => { jestExpect(() => {
// eslint-disable-next-line no-throw-literal // eslint-disable-next-line no-throw-literal
throw 404; throw 404;
}).not.toThrow(/^[123456789]\d*/); }).not.toThrow(/^[1-9]\d*/);
}).toThrowErrorMatchingSnapshot(); }).toThrowErrorMatchingSnapshot();
}); });
}); });

View File

@ -77,14 +77,10 @@ export function check(argv: Config.Argv): true {
if ( if (
argv.config && argv.config &&
!isJSONString(argv.config) && !isJSONString(argv.config) &&
!argv.config.match( !new RegExp(
new RegExp( `\\.(${constants.JEST_CONFIG_EXT_ORDER.map(e => e.slice(1)).join('|')})$`,
`\\.(${constants.JEST_CONFIG_EXT_ORDER.map(e => e.slice(1)).join( 'i',
'|', ).test(argv.config)
)})$`,
'i',
),
)
) { ) {
throw new Error( throw new Error(
`The --config option requires a JSON string literal, or a file path with one of these extensions: ${constants.JEST_CONFIG_EXT_ORDER.join( `The --config option requires a JSON string literal, or a file path with one of these extensions: ${constants.JEST_CONFIG_EXT_ORDER.join(

View File

@ -1100,7 +1100,7 @@ describe('preset', () => {
); );
const errorMessage = semver.satisfies(process.versions.node, '<19.0.0') const errorMessage = semver.satisfies(process.versions.node, '<19.0.0')
? /Unexpected token } in JSON at position (104|110)[\s\S]* at / ? /Unexpected token } in JSON at position (104|110)[\S\s]* at /
: 'SyntaxError: Expected double-quoted property name in JSON at position 104'; : 'SyntaxError: Expected double-quoted property name in JSON at position 104';
await expect( await expect(
@ -1125,7 +1125,7 @@ describe('preset', () => {
); );
const errorMessage = semver.satisfies(process.versions.node, '<16.9.1') const errorMessage = semver.satisfies(process.versions.node, '<16.9.1')
? /TypeError: Cannot read property 'call' of undefined[\s\S]* at / ? /TypeError: Cannot read property 'call' of undefined[\S\s]* at /
: "TypeError: Cannot read properties of undefined (reading 'call')"; : "TypeError: Cannot read properties of undefined (reading 'call')";
await expect( await expect(

View File

@ -33,7 +33,7 @@ function stringToBytes(
if (isNaN(Number.parseFloat(input.slice(-1)))) { if (isNaN(Number.parseFloat(input.slice(-1)))) {
// eslint-disable-next-line prefer-const // eslint-disable-next-line prefer-const
let [, numericString, trailingChars] = let [, numericString, trailingChars] =
input.match(/(.*?)([^0-9.-]+)$/i) || []; input.match(/(.*?)([^\d.-]+)$/i) || [];
if (trailingChars && numericString) { if (trailingChars && numericString) {
const numericValue = Number.parseFloat(numericString); const numericValue = Number.parseFloat(numericString);

View File

@ -52,7 +52,7 @@ export const resolve = (
}; };
export const escapeGlobCharacters = (path: string): string => export const escapeGlobCharacters = (path: string): string =>
path.replace(/([()*{}[\]!?\\])/g, '\\$1'); path.replace(/([!()*?[\\\]{}])/g, '\\$1');
export const replaceRootDirInPath = ( export const replaceRootDirInPath = (
rootDir: string, rootDir: string,

View File

@ -13,11 +13,11 @@ type Pragmas = Record<string, string | Array<string>>;
const commentEndRe = /\*\/$/; const commentEndRe = /\*\/$/;
const commentStartRe = /^\/\*\*?/; const commentStartRe = /^\/\*\*?/;
const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g; const lineCommentRe = /(^|\s+)\/\/([^\n\r]*)/g;
const ltrimNewlineRe = /^(\r?\n)+/; const ltrimNewlineRe = /^(\r?\n)+/;
const multilineRe = const multilineRe =
/(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g; /(?:^|\r?\n) *(@[^\n\r]*?) *\r?\n *(?![^\n\r@]*\/\/[^]*)([^\s@][^\n\r@]+?) *\r?\n/g;
const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\n\r]*)/g;
const stringStartRe = /(\r?\n|^) *\* ?/g; const stringStartRe = /(\r?\n|^) *\* ?/g;
const STRING_ARRAY: ReadonlyArray<string> = []; const STRING_ARRAY: ReadonlyArray<string> = [];

View File

@ -12,7 +12,7 @@ import {format as pretty} from 'pretty-format';
import type {EachTests} from '../bind'; import type {EachTests} from '../bind';
import {type Templates, interpolateVariables} from './interpolation'; import {type Templates, interpolateVariables} from './interpolation';
const SUPPORTED_PLACEHOLDERS = /%[sdifjoOp#]/g; const SUPPORTED_PLACEHOLDERS = /%[#Odfijops]/g;
const PRETTY_PLACEHOLDER = '%p'; const PRETTY_PLACEHOLDER = '%p';
const INDEX_PLACEHOLDER = '%#'; const INDEX_PLACEHOLDER = '%#';
const PLACEHOLDER_PREFIX = '%'; const PLACEHOLDER_PREFIX = '%';

View File

@ -10,7 +10,7 @@
const blockCommentRe = /\/\*[^]*?\*\//g; const blockCommentRe = /\/\*[^]*?\*\//g;
const lineCommentRe = /\/\/.*/g; const lineCommentRe = /\/\/.*/g;
const LOAD_MODULE_RE = const LOAD_MODULE_RE =
/(?:^|[^.]\s*)(\bloadModule\s*?\(\s*?)([`'"])([^`'"]+)(\2\s*?\))/g; /(?:^|[^.]\s*)(\bloadModule\s*?\(\s*?)(["'`])([^"'`]+)(\2\s*?\))/g;
export function extract(code, filePath, defaultDependencyExtractor) { export function extract(code, filePath, defaultDependencyExtractor) {
const dependencies = defaultDependencyExtractor(code); const dependencies = defaultDependencyExtractor(code);

View File

@ -116,16 +116,16 @@ exports[`on node >=15.0.0 should return the inner errors of an AggregateError 1`
AggregateError: AggregateError:
<dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:588:22)</intensity> <dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:586:22)</intensity>
Errors contained in AggregateError: Errors contained in AggregateError:
Err 1 Err 1
<dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:589:7)</intensity> <dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:587:7)</intensity>
Err 2 Err 2
<dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:590:7)</intensity> <dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:588:7)</intensity>
" "
`; `;
@ -177,12 +177,12 @@ exports[`should return the error cause if there is one 1`] = `
Test exception Test exception
<dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:567:17)</intensity> <dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:565:17)</intensity>
Cause: Cause:
Cause Error Cause Error
<dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:570:17)</intensity> <dim>at Object.<anonymous> (</intensity>packages/jest-message-util/src/__tests__/messages.test.ts<dim>:568:17)</intensity>
" "
`; `;

View File

@ -36,7 +36,7 @@ const unixStackTrace =
at Object.it (build/__tests__/messages-test.js:45:41) at Object.it (build/__tests__/messages-test.js:45:41)
at Object.<anonymous> (../jest-jasmine2/build/jasmine-pit.js:35:32) at Object.<anonymous> (../jest-jasmine2/build/jasmine-pit.js:35:32)
at attemptAsync (../jest-jasmine2/build/jasmine-2.4.1.js:1919:24)`; at attemptAsync (../jest-jasmine2/build/jasmine-2.4.1.js:1919:24)`;
const unixError = new Error(unixStackTrace.replace(/\n\s*at [\s\s]*/m, '')); const unixError = new Error(unixStackTrace.replace(/\n\s*at \s*/m, ''));
unixError.stack = unixStackTrace; unixError.stack = unixStackTrace;
const assertionStack = const assertionStack =
@ -59,9 +59,7 @@ const assertionStack =
at process._tickCallback (internal/process/next_tick.js:188:7) at process._tickCallback (internal/process/next_tick.js:188:7)
at internal/process/next_tick.js:188:7 at internal/process/next_tick.js:188:7
`; `;
const assertionError = new Error( const assertionError = new Error(assertionStack.replace(/\n\s*at \s*/m, ''));
assertionStack.replace(/\n\s*at [\s\s]*/m, ''),
);
assertionError.stack = assertionStack; assertionError.stack = assertionStack;
const vendorStack = const vendorStack =
@ -90,7 +88,7 @@ const babelStack =
\u001b[90m 22 | \u001b[39m )\u001b[33m;\u001b[39m \u001b[90m 22 | \u001b[39m )\u001b[33m;\u001b[39m
\u001b[90m 23 | \u001b[39m } \u001b[36melse\u001b[39m \u001b[36mif\u001b[39m (\u001b[36mtypeof\u001b[39m render \u001b[33m!==\u001b[39m \u001b[32m'function'\u001b[39m) {\u001b[0m \u001b[90m 23 | \u001b[39m } \u001b[36melse\u001b[39m \u001b[36mif\u001b[39m (\u001b[36mtypeof\u001b[39m render \u001b[33m!==\u001b[39m \u001b[32m'function'\u001b[39m) {\u001b[0m
`; `;
const babelError = new Error(babelStack.replace(/\n\s*at [\s\s]*/m, '')); const babelError = new Error(babelStack.replace(/\n\s*at \s*/m, ''));
babelError.stack = babelStack; babelError.stack = babelStack;
function buildErrorWithCause(message: string, opts: {cause: unknown}): Error { function buildErrorWithCause(message: string, opts: {cause: unknown}): Error {

View File

@ -74,7 +74,7 @@ const trim = (string: string) => (string || '').trim();
// want to trim those, because they may have pointers to the column/character // want to trim those, because they may have pointers to the column/character
// which will get misaligned. // which will get misaligned.
const trimPaths = (string: string) => const trimPaths = (string: string) =>
string.match(STACK_PATH_REGEXP) ? trim(string) : string; STACK_PATH_REGEXP.test(string) ? trim(string) : string;
const getRenderedCallsite = ( const getRenderedCallsite = (
fileContent: string, fileContent: string,
@ -292,7 +292,7 @@ export const formatPath = (
relativeTestPath: string | null = null, relativeTestPath: string | null = null,
): string => { ): string => {
// Extract the file path from the trace line. // Extract the file path from the trace line.
const match = line.match(/(^\s*at .*?\(?)([^()]+)(:[0-9]+:[0-9]+\)?.*$)/); const match = line.match(/(^\s*at .*?\(?)([^()]+)(:\d+:\d+\)?.*$)/);
if (!match) { if (!match) {
return line; return line;
} }
@ -528,7 +528,7 @@ export const separateMessageFromStack = (
// If the error is a plain "Error:" instead of a SyntaxError or TypeError we // If the error is a plain "Error:" instead of a SyntaxError or TypeError we
// remove the prefix from the message because it is generally not useful. // remove the prefix from the message because it is generally not useful.
const messageMatch = content.match( const messageMatch = content.match(
/^(?:Error: )?([\s\S]*?(?=\n\s*at\s.*:\d*:\d*)|\s*.*)([\s\S]*)$/, /^(?:Error: )?([\S\s]*?(?=\n\s*at\s.*:\d*:\d*)|\s*.*)([\S\s]*)$/,
); );
if (!messageMatch) { if (!messageMatch) {
// For typescript // For typescript

View File

@ -1047,7 +1047,7 @@ export class ModuleMocker {
if ( if (
type === 'function' && type === 'function' &&
this.isMockFunction(component) && this.isMockFunction(component) &&
slot.match(/^mock/) slot.startsWith('mock')
) { ) {
continue; continue;
} }

View File

@ -18,12 +18,12 @@ export const escapePathForRegex = (dir: string): string => {
}; };
export const escapeStrForRegex = (string: string): string => export const escapeStrForRegex = (string: string): string =>
string.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&'); string.replace(/[$()*+.?[\\\]^{|}]/g, '\\$&');
export const replacePathSepForRegex = (string: string): string => { export const replacePathSepForRegex = (string: string): string => {
if (sep === '\\') { if (sep === '\\') {
return string.replace( return string.replace(
/(\/|(.)?\\(?![[\]{}()*+?.^$|\\]))/g, /(\/|(.)?\\(?![$()*+.?[\\\]^{|}]))/g,
(_match, _, p2) => (p2 && p2 !== '\\' ? `${p2}\\\\` : '\\\\'), (_match, _, p2) => (p2 && p2 !== '\\' ? `${p2}\\\\` : '\\\\'),
); );
} }

View File

@ -108,7 +108,7 @@ const replInstance: repl.REPLServer = repl.start({
}); });
replInstance.context.require = (moduleName: string) => { replInstance.context.require = (moduleName: string) => {
if (/(\/|\\|\.)/.test(moduleName)) { if (/([./\\])/.test(moduleName)) {
moduleName = path.resolve(process.cwd(), moduleName); moduleName = path.resolve(process.cwd(), moduleName);
} }
return require(moduleName) as unknown; return require(moduleName) as unknown;

View File

@ -438,7 +438,7 @@ export default class Resolver {
return matches return matches
? (moduleName: string) => ? (moduleName: string) =>
moduleName.replace( moduleName.replace(
/\$([0-9]+)/g, /\$(\d+)/g,
(_, index) => matches[parseInt(index, 10)] || '', (_, index) => matches[parseInt(index, 10)] || '',
) )
: (moduleName: string) => moduleName; : (moduleName: string) => moduleName;

View File

@ -80,7 +80,9 @@ export default function shouldInstrument(
} }
if ( if (
config.coveragePathIgnorePatterns.some(pattern => !!filename.match(pattern)) config.coveragePathIgnorePatterns.some(pattern =>
new RegExp(pattern).test(filename),
)
) { ) {
return false; return false;
} }

View File

@ -35,12 +35,12 @@ export default class TestPathPatterns {
const regexString = this.patterns const regexString = this.patterns
.map(p => { .map(p => {
// absolute paths passed on command line should stay same // absolute paths passed on command line should stay same
if (p.match(/^\//)) { if (/^\//.test(p)) {
return p; return p;
} }
// explicit relative paths should resolve against rootDir // explicit relative paths should resolve against rootDir
if (p.match(/^\.\//)) { if (/^\.\//.test(p)) {
return p.replace(/^\.\//, rootDirRegex); return p.replace(/^\.\//, rootDirRegex);
} }

View File

@ -6,5 +6,5 @@
*/ */
export default function replacePathSepForGlob(path: string): string { export default function replacePathSepForGlob(path: string): string {
return path.replace(/\\(?![{}()+?.^$])/g, '/'); return path.replace(/\\(?![$()+.?^{}])/g, '/');
} }

View File

@ -183,7 +183,7 @@ function printBasicValue(
if (toStringed === '[object RegExp]') { if (toStringed === '[object RegExp]') {
if (escapeRegex) { if (escapeRegex) {
// https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js // https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js
return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); return regExpToString.call(val).replace(/[$()*+.?[\\\]^{|}]/g, '\\$&');
} }
return regExpToString.call(val); return regExpToString.call(val);
} }

View File

@ -8,7 +8,7 @@
import fs from 'graceful-fs'; import fs from 'graceful-fs';
const linkRegex = const linkRegex =
/\[#(\d+)\]\(https:\/\/github.com\/facebook\/jest\/(issues|pull)\/(\d+)\)/g; /\[#(\d+)]\(https:\/\/github.com\/facebook\/jest\/(issues|pull)\/(\d+)\)/g;
const changelogPath = 'CHANGELOG.md'; const changelogPath = 'CHANGELOG.md';
const data = fs.readFileSync(changelogPath, 'utf-8'); const data = fs.readFileSync(changelogPath, 'utf-8');