Skip to content

Commit

Permalink
chore: enable lint rule for better RegExpes (jestjs#14803)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Dec 29, 2023
1 parent 5a21906 commit eaea490
Show file tree
Hide file tree
Showing 32 changed files with 60 additions and 74 deletions.
2 changes: 0 additions & 2 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,6 @@ module.exports = {
'unicorn/prefer-reflect-apply': 'off',

// TODO: turn on at some point
'unicorn/better-regex': 'off',
'unicorn/catch-error-name': 'off',
'unicorn/consistent-function-scoping': 'off',
'unicorn/error-message': 'off',
Expand Down Expand Up @@ -713,7 +712,6 @@ module.exports = {
'unicorn/prefer-number-properties': 'off',
'unicorn/prefer-object-from-entries': 'off',
'unicorn/prefer-prototype-methods': 'off',
'unicorn/prefer-regexp-test': 'off',
'unicorn/prefer-spread': 'off',
'unicorn/prefer-string-replace-all': 'off',
'unicorn/prevent-abbreviations': 'off',
Expand Down
2 changes: 1 addition & 1 deletion e2e/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ export const createEmptyPackage = (

export const extractSummary = (stdout: string) => {
const match = stdout
.replace(/(?:\\[rn])+/g, '\n')
.replace(/(?:\\[nr])+/g, '\n')
.match(
/(Seed:.*\n)?Test Suites:.*\nTests.*\nSnapshots.*\nTime.*(\nRan all test suites)*.*\n*$/gm,
);
Expand Down
4 changes: 2 additions & 2 deletions e2e/__tests__/failures.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import runJest from '../runJest';

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) {
const {rest} = extractSummary(stderr);
Expand Down Expand Up @@ -65,7 +65,7 @@ test('works with async failures', () => {
const result = normalizeDots(rest)
.replace(/.*thrown:.*\n/, '')
.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>',
)
.replace(/.*Timeout - Async callback was not.*/, '<REPLACED>');
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/jasmineAsync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ describe('async jasmine', () => {
expect(json.numPendingTests).toBe(1);
expect(json.testResults[0].message).toMatch(/concurrent test fails/);
if (!isJestJasmineRun()) {
expect(stderr.match(/\[\[\w+\]\]/g)).toEqual([
expect(stderr.match(/\[\[\w+]]/g)).toEqual([
'[[beforeAll]]',
'[[test]]',
'[[test]]',
Expand Down
4 changes: 2 additions & 2 deletions e2e/__tests__/runProgrammatically.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ const dir = resolve(__dirname, '..', 'run-programmatically');

test('run Jest programmatically cjs', () => {
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', () => {
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$/);
});
2 changes: 1 addition & 1 deletion e2e/__tests__/showConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ test('--showConfig outputs config info and exits', () => {

stdout = stdout
.replace(/\\\\node_modules\\\\/g, 'node_modules')
.replace(/\\\\\.pnp\\\\\.\[\^[/\\]+\]\+\$/g, '<<REPLACED_PNP_PATH>>')
.replace(/\\\\\.pnp\\\\\.\[\^[/\\]+]\+\$/g, '<<REPLACED_PNP_PATH>>')
.replace(/\\\\(?:([^.]+?)|$)/g, '/$1')
.replace(/"cacheDirectory": "(.+)"/g, '"cacheDirectory": "/tmp/jest"')
.replace(/"id": "(.+)"/g, '"id": "[md5 hash]"')
Expand Down
24 changes: 8 additions & 16 deletions e2e/__tests__/stackTrace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ describe('Stack Trace', () => {
/ReferenceError: thisIsARuntimeError is not defined/,
);
expect(stderr).toMatch(/> 10 \| thisIsARuntimeError\(\);/);
expect(stderr).toMatch(
/\s+at\s(?:.+?)\s\(__tests__\/runtimeError.test\.js/,
);
expect(stderr).toMatch(/\s+at\s.+?\s\(__tests__\/runtimeError.test\.js/);
});

it('does not print a stack trace for runtime errors when --noStackTrace is given', () => {
Expand All @@ -37,7 +35,7 @@ describe('Stack Trace', () => {
/ReferenceError: thisIsARuntimeError is not defined/,
);
expect(stderr).not.toMatch(
/\s+at\s(?:.+?)\s\(__tests__\/runtimeError.test\.js/,
/\s+at\s.+?\s\(__tests__\/runtimeError.test\.js/,
);
});

Expand All @@ -47,7 +45,7 @@ describe('Stack Trace', () => {
expect(extractSummary(stderr).summary).toMatchSnapshot();
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', () => {
Expand All @@ -59,9 +57,7 @@ describe('Stack Trace', () => {
expect(extractSummary(stderr).summary).toMatchSnapshot();
expect(exitCode).toBe(1);

expect(stderr).not.toMatch(
/\s+at\s(?:.+?)\s\(__tests__\/stackTrace.test\.js/,
);
expect(stderr).not.toMatch(/\s+at\s.+?\s\(__tests__\/stackTrace.test\.js/);
});

it('prints a stack trace for errors', () => {
Expand All @@ -73,16 +69,14 @@ describe('Stack Trace', () => {
expect(stderr).toMatch(/this is unexpected\./);
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
expect(stderr).toMatch(
/Cannot find module 'this-module-does-not-exist' from '__tests__\/testError\.test\.js'/,
);

expect(stderr).toMatch(
/\s+at\s(?:.+?)\s\((?:.+?)jest-resolve\/build\/index\.js/,
);
expect(stderr).toMatch(/\s+at\s.+?\s\(.+?jest-resolve\/build\/index\.js/);
});

it('prints a stack trace for errors without message in stack trace', () => {
Expand All @@ -95,7 +89,7 @@ describe('Stack Trace', () => {

expect(stderr).toMatch(/important message/);
expect(stderr).toMatch(
/\s+at\s(?:.+?)\s\(__tests__\/stackTraceWithoutMessage.test\.js/,
/\s+at\s.+?\s\(__tests__\/stackTraceWithoutMessage.test\.js/,
);
});

Expand All @@ -108,8 +102,6 @@ describe('Stack Trace', () => {
expect(extractSummary(stderr).summary).toMatchSnapshot();
expect(exitCode).toBe(1);

expect(stderr).not.toMatch(
/\s+at\s(?:.+?)\s\(__tests__\/testError.test\.js/,
);
expect(stderr).not.toMatch(/\s+at\s.+?\s\(__tests__\/testError.test\.js/);
});
});
2 changes: 1 addition & 1 deletion e2e/__tests__/version.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ test('works with jest.config.js', () => {
});

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
expect(stdout.split(/\n/)).toHaveLength(1);
expect(stderr).toBe('');
Expand Down
2 changes: 1 addition & 1 deletion e2e/snapshot-escape/__tests__/snapshotEscapeRegex.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
'use strict';

const regex = /\dd \s+ \w \\\[ \. blahzz.* [xyz]+/;
const regex = /\dd \s+ \w \\\[ \. blahzz.* [x-z]+/;

test('escape regex', () => expect(regex).toMatchSnapshot());

Expand Down
2 changes: 1 addition & 1 deletion packages/expect-utils/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ export function emptyObject(obj: unknown): boolean {
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 =>
typeof expected === 'string' &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ Received message: <r>"apple"</>
exports[`toThrow regexp threw, but message did not match (non-error falsey) 1`] = `
<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</>

`;
Expand All @@ -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`] = `
<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</>

`;
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/src/__tests__/matchers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1817,7 +1817,7 @@ describe('.toMatch()', () => {
});

it('does not maintain RegExp state between calls', () => {
const regex = /[f]\d+/gi;
const regex = /f\d+/gi;
jestExpect('f123').toMatch(regex);
jestExpect('F456').toMatch(regex);
jestExpect(regex.lastIndex).toBe(0);
Expand Down
4 changes: 2 additions & 2 deletions packages/expect/src/__tests__/toThrowMatchers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ describe('toThrow', () => {
jestExpect(() => {
// eslint-disable-next-line no-throw-literal
throw 0;
}).toThrow(/^[123456789]\d*/);
}).toThrow(/^[1-9]\d*/);
}).toThrowErrorMatchingSnapshot();
});

Expand All @@ -138,7 +138,7 @@ describe('toThrow', () => {
jestExpect(() => {
// eslint-disable-next-line no-throw-literal
throw 404;
}).not.toThrow(/^[123456789]\d*/);
}).not.toThrow(/^[1-9]\d*/);
}).toThrowErrorMatchingSnapshot();
});
});
Expand Down
12 changes: 4 additions & 8 deletions packages/jest-cli/src/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,10 @@ export function check(argv: Config.Argv): true {
if (
argv.config &&
!isJSONString(argv.config) &&
!argv.config.match(
new RegExp(
`\\.(${constants.JEST_CONFIG_EXT_ORDER.map(e => e.slice(1)).join(
'|',
)})$`,
'i',
),
)
!new RegExp(
`\\.(${constants.JEST_CONFIG_EXT_ORDER.map(e => e.slice(1)).join('|')})$`,
'i',
).test(argv.config)
) {
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(
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-config/src/__tests__/normalize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1100,7 +1100,7 @@ describe('preset', () => {
);

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';

await expect(
Expand All @@ -1125,7 +1125,7 @@ describe('preset', () => {
);

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')";

await expect(
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-config/src/stringToBytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function stringToBytes(
if (isNaN(Number.parseFloat(input.slice(-1)))) {
// eslint-disable-next-line prefer-const
let [, numericString, trailingChars] =
input.match(/(.*?)([^0-9.-]+)$/i) || [];
input.match(/(.*?)([^\d.-]+)$/i) || [];

if (trailingChars && numericString) {
const numericValue = Number.parseFloat(numericString);
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.replace(/([!()*?[\\\]{}])/g, '\\$1');

export const replaceRootDirInPath = (
rootDir: string,
Expand Down
6 changes: 3 additions & 3 deletions packages/jest-docblock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ type Pragmas = Record<string, string | Array<string>>;
const commentEndRe = /\*\/$/;
const commentStartRe = /^\/\*\*?/;
const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
const lineCommentRe = /(^|\s+)\/\/([^\n\r]*)/g;
const ltrimNewlineRe = /^(\r?\n)+/;
const multilineRe =
/(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
/(?:^|\r?\n) *(@[^\n\r]*?) *\r?\n *(?![^\n\r@]*\/\/[^]*)([^\s@][^\n\r@]+?) *\r?\n/g;
const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\n\r]*)/g;
const stringStartRe = /(\r?\n|^) *\* ?/g;
const STRING_ARRAY: ReadonlyArray<string> = [];

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-each/src/table/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {format as pretty} from 'pretty-format';
import type {EachTests} from '../bind';
import {type Templates, interpolateVariables} from './interpolation';

const SUPPORTED_PLACEHOLDERS = /%[sdifjoOp#]/g;
const SUPPORTED_PLACEHOLDERS = /%[#Odfijops]/g;
const PRETTY_PLACEHOLDER = '%p';
const INDEX_PLACEHOLDER = '%#';
const PLACEHOLDER_PREFIX = '%';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
const blockCommentRe = /\/\*[^]*?\*\//g;
const lineCommentRe = /\/\/.*/g;
const LOAD_MODULE_RE =
/(?:^|[^.]\s*)(\bloadModule\s*?\(\s*?)([`'"])([^`'"]+)(\2\s*?\))/g;
/(?:^|[^.]\s*)(\bloadModule\s*?\(\s*?)(["'`])([^"'`]+)(\2\s*?\))/g;

export function extract(code, filePath, defaultDependencyExtractor) {
const dependencies = defaultDependencyExtractor(code);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,16 @@ exports[`on node >=15.0.0 should return the inner errors of an AggregateError 1`
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:
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
<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>
"
`;
Expand Down Expand Up @@ -177,12 +177,12 @@ exports[`should return the error cause if there is one 1`] = `
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 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>
"
`;
8 changes: 3 additions & 5 deletions packages/jest-message-util/src/__tests__/messages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const unixStackTrace =
at Object.it (build/__tests__/messages-test.js:45:41)
at Object.<anonymous> (../jest-jasmine2/build/jasmine-pit.js:35:32)
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;

const assertionStack =
Expand All @@ -59,9 +59,7 @@ const assertionStack =
at process._tickCallback (internal/process/next_tick.js:188:7)
at internal/process/next_tick.js:188:7
`;
const assertionError = new Error(
assertionStack.replace(/\n\s*at [\s\s]*/m, ''),
);
const assertionError = new Error(assertionStack.replace(/\n\s*at \s*/m, ''));
assertionError.stack = assertionStack;

const vendorStack =
Expand Down Expand Up @@ -90,7 +88,7 @@ const babelStack =
\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
`;
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;

function buildErrorWithCause(message: string, opts: {cause: unknown}): Error {
Expand Down
Loading

0 comments on commit eaea490

Please sign in to comment.