diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 802fa58a9215..79dcbadf3e31 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -595,6 +595,7 @@ module.exports = { yoda: 'off', 'unicorn/explicit-length-check': 'error', + 'unicorn/no-array-for-each': 'error', 'unicorn/no-negated-condition': 'error', 'unicorn/prefer-default-parameters': 'error', 'unicorn/prefer-includes': 'error', diff --git a/e2e/MockStdinWatchPlugin.js b/e2e/MockStdinWatchPlugin.js index 55448bd26688..631ef92e8b39 100644 --- a/e2e/MockStdinWatchPlugin.js +++ b/e2e/MockStdinWatchPlugin.js @@ -20,7 +20,7 @@ class MockStdinWatchPlugin { apply(jestHooks) { jestHooks.onTestRunComplete(() => { const {keys} = this._config.input.shift(); - keys.forEach(key => this._stdin.emit('data', key)); + for (const key of keys) this._stdin.emit('data', key); }); } } diff --git a/e2e/Utils.ts b/e2e/Utils.ts index 31757a49891c..1d316c1ec926 100644 --- a/e2e/Utils.ts +++ b/e2e/Utils.ts @@ -128,7 +128,7 @@ export const writeFiles = ( files: {[filename: string]: string}, ) => { fs.mkdirSync(directory, {recursive: true}); - Object.keys(files).forEach(fileOrPath => { + for (const fileOrPath of Object.keys(files)) { const dirname = path.dirname(fileOrPath); if (dirname !== '/') { @@ -138,7 +138,7 @@ export const writeFiles = ( path.resolve(directory, ...fileOrPath.split('/')), dedent(files[fileOrPath]), ); - }); + } }; export const writeSymlinks = ( @@ -146,7 +146,7 @@ export const writeSymlinks = ( symlinks: {[existingFile: string]: string}, ) => { fs.mkdirSync(directory, {recursive: true}); - Object.keys(symlinks).forEach(fileOrPath => { + for (const fileOrPath of Object.keys(symlinks)) { const symLinkPath = symlinks[fileOrPath]; const dirname = path.dirname(symLinkPath); @@ -158,7 +158,7 @@ export const writeSymlinks = ( path.resolve(directory, ...symLinkPath.split('/')), 'junction', ); - }); + } }; const NUMBER_OF_TESTS_TO_FORCE_USING_WORKERS = 25; diff --git a/e2e/__tests__/coverageRemapping.test.ts b/e2e/__tests__/coverageRemapping.test.ts index 73fc31b291cf..f37282ab2da5 100644 --- a/e2e/__tests__/coverageRemapping.test.ts +++ b/e2e/__tests__/coverageRemapping.test.ts @@ -27,11 +27,11 @@ it('maps code coverage against original source', () => { const coverageMap = JSON.parse(readFileSync(coverageMapFile, 'utf-8')); // reduce absolute paths embedded in the coverage map to just filenames - Object.keys(coverageMap).forEach(filename => { + for (const filename of Object.keys(coverageMap)) { coverageMap[filename].path = path.basename(coverageMap[filename].path); delete coverageMap[filename].hash; coverageMap[path.basename(filename)] = coverageMap[filename]; delete coverageMap[filename]; - }); + } expect(coverageMap).toMatchSnapshot(); }); diff --git a/e2e/__tests__/coverageTransformInstrumented.test.ts b/e2e/__tests__/coverageTransformInstrumented.test.ts index 8ae525dce4cb..8704a81c6f32 100644 --- a/e2e/__tests__/coverageTransformInstrumented.test.ts +++ b/e2e/__tests__/coverageTransformInstrumented.test.ts @@ -27,11 +27,11 @@ it('code coverage for transform instrumented code', () => { const coverageMap = JSON.parse(readFileSync(coverageMapFile, 'utf-8')); // reduce absolute paths embedded in the coverage map to just filenames - Object.keys(coverageMap).forEach(filename => { + for (const filename of Object.keys(coverageMap)) { coverageMap[filename].path = path.basename(coverageMap[filename].path); delete coverageMap[filename].hash; coverageMap[path.basename(filename)] = coverageMap[filename]; delete coverageMap[filename]; - }); + } expect(coverageMap).toMatchSnapshot(); }); diff --git a/e2e/__tests__/errorOnDeprecated.test.ts b/e2e/__tests__/errorOnDeprecated.test.ts index 6bdfec2c7ec6..21023e9ce2e0 100644 --- a/e2e/__tests__/errorOnDeprecated.test.ts +++ b/e2e/__tests__/errorOnDeprecated.test.ts @@ -31,7 +31,7 @@ const SHOULD_NOT_PASS_IN_JEST = new Set([ 'spyOnProperty.test.js', ]); -testFiles.forEach(testFile => { +for (const testFile of testFiles) { test(`${testFile} errors in errorOnDeprecated mode`, () => { const result = runJest('error-on-deprecated', [ testFile, @@ -42,9 +42,9 @@ testFiles.forEach(testFile => { expect(rest).toMatchSnapshot(); }); -}); +} -testFiles.forEach(testFile => { +for (const testFile of testFiles) { const shouldPass = SHOULD_NOT_PASS_IN_JEST.has(testFile); const expectation = `${testFile} ${shouldPass ? 'errors' : 'passes'}`; @@ -54,4 +54,4 @@ testFiles.forEach(testFile => { const result = runJest('error-on-deprecated', [testFile]); expect(result.exitCode).toBe(shouldPass ? 1 : 0); }); -}); +} diff --git a/e2e/__tests__/snapshot.test.ts b/e2e/__tests__/snapshot.test.ts index 849effdfde28..ab664eaad1bb 100644 --- a/e2e/__tests__/snapshot.test.ts +++ b/e2e/__tests__/snapshot.test.ts @@ -70,7 +70,7 @@ const getSnapshotOfCopy = () => { describe('Snapshot', () => { const cleanup = () => { - [ + for (const file of [ snapshotFile, secondSnapshotFile, snapshotOfCopy, @@ -78,11 +78,11 @@ describe('Snapshot', () => { snapshotEscapeFile, snapshotEscapeRegexFile, snapshotEscapeSubstitutionFile, - ].forEach(file => { + ]) { if (fileExists(file)) { fs.unlinkSync(file); } - }); + } if (fileExists(snapshotDir)) { fs.rmdirSync(snapshotDir); } diff --git a/e2e/__tests__/summaryThreshold.test.ts b/e2e/__tests__/summaryThreshold.test.ts index 5d4c9e89ccef..1a5e205603d7 100644 --- a/e2e/__tests__/summaryThreshold.test.ts +++ b/e2e/__tests__/summaryThreshold.test.ts @@ -7,7 +7,7 @@ import runJest from '../runJest'; -['default', 'summary'].forEach(reporter => { +for (const reporter of ['default', 'summary']) { describe(`${reporter} reporter`, () => { test('prints failure messages when total number of test suites is over summaryThreshold', () => { const {exitCode, stderr} = runJest('summary-threshold', [ @@ -26,4 +26,4 @@ import runJest from '../runJest'; ); }); }); -}); +} diff --git a/e2e/__tests__/transform.test.ts b/e2e/__tests__/transform.test.ts index 5e68ba87fbc6..458a014f232e 100644 --- a/e2e/__tests__/transform.test.ts +++ b/e2e/__tests__/transform.test.ts @@ -199,9 +199,9 @@ describe('transformer caching', () => { const loggedFiles = stdout.split('\n'); // Verify any lines logged are _just_ the file we care about - loggedFiles.forEach(line => { + for (const line of loggedFiles) { expect(line).toBe(transformedFile); - }); + } // We run with 2 workers, so the file should be transformed twice expect(loggedFiles).toHaveLength(2); diff --git a/e2e/__tests__/watchModeOnlyFailed.test.ts b/e2e/__tests__/watchModeOnlyFailed.test.ts index 4d36586180b7..8d6fd7c3e2f7 100644 --- a/e2e/__tests__/watchModeOnlyFailed.test.ts +++ b/e2e/__tests__/watchModeOnlyFailed.test.ts @@ -41,9 +41,9 @@ test('can press "f" to run only failed tests', () => { const results = extractSummaries(stderr); expect(results).toHaveLength(2); - results.forEach(({rest, summary}) => { + for (const {rest, summary} of results) { expect(rest).toMatchSnapshot('test results'); expect(summary).toMatchSnapshot('test summary'); - }); + } expect(exitCode).toBe(0); }); diff --git a/e2e/__tests__/watchModePatterns.test.ts b/e2e/__tests__/watchModePatterns.test.ts index d5e3534c73b0..dd4bc246d1fe 100644 --- a/e2e/__tests__/watchModePatterns.test.ts +++ b/e2e/__tests__/watchModePatterns.test.ts @@ -47,10 +47,10 @@ test('can press "p" to filter by file name', () => { expect(stdout).toMatchSnapshot(); expect(results).toHaveLength(2); - results.forEach(({rest, summary}) => { + for (const {rest, summary} of results) { expect(rest).toMatchSnapshot('test results'); expect(summary).toMatchSnapshot('test summary'); - }); + } expect(exitCode).toBe(0); }); @@ -66,9 +66,9 @@ test('can press "t" to filter by test name', () => { expect(stdout).toMatchSnapshot(); expect(results).toHaveLength(2); - results.forEach(({rest, summary}) => { + for (const {rest, summary} of results) { expect(rest).toMatchSnapshot('test results'); expect(summary).toMatchSnapshot('test summary'); - }); + } expect(exitCode).toBe(0); }); diff --git a/e2e/__tests__/watchModeUpdateSnapshot.test.ts b/e2e/__tests__/watchModeUpdateSnapshot.test.ts index 14dabb0ee89a..72332142fd96 100644 --- a/e2e/__tests__/watchModeUpdateSnapshot.test.ts +++ b/e2e/__tests__/watchModeUpdateSnapshot.test.ts @@ -46,9 +46,9 @@ test('can press "u" to update snapshots', () => { const {exitCode, stderr} = runJest(DIR, ['--no-watchman', '--watchAll']); const results = extractSummaries(stderr); expect(results).toHaveLength(2); - results.forEach(({rest, summary}) => { + for (const {rest, summary} of results) { expect(rest).toMatchSnapshot('test results'); expect(summary).toMatchSnapshot('test summary'); - }); + } expect(exitCode).toBe(0); }); diff --git a/e2e/custom-reporters/reporters/AssertionCountsReporter.js b/e2e/custom-reporters/reporters/AssertionCountsReporter.js index 67523ce19930..7777efd828b0 100644 --- a/e2e/custom-reporters/reporters/AssertionCountsReporter.js +++ b/e2e/custom-reporters/reporters/AssertionCountsReporter.js @@ -9,13 +9,13 @@ class AssertionCountsReporter { onTestFileResult(test, testResult, aggregatedResult) { - testResult.testResults.forEach((testCaseResult, index) => { + for (const [index, testCaseResult] of testResult.testResults.entries()) { console.log( `onTestFileResult testCaseResult ${index}: ${testCaseResult.title}, ` + `status: ${testCaseResult.status}, ` + `numExpectations: ${testCaseResult.numPassingAsserts}`, ); - }); + } } onTestCaseResult(test, testCaseResult) { console.log( diff --git a/e2e/jasmine-async/__tests__/returningValues.test.js b/e2e/jasmine-async/__tests__/returningValues.test.js index 8fcdac84444c..32ec21cf6db0 100644 --- a/e2e/jasmine-async/__tests__/returningValues.test.js +++ b/e2e/jasmine-async/__tests__/returningValues.test.js @@ -8,7 +8,7 @@ 'use strict'; describe('returning values', () => { - [ + for (const val of [ 1, 'string', 0.1, @@ -20,7 +20,7 @@ describe('returning values', () => { [1], {}, () => {}, - ].forEach(val => { + ]) { it(`throws if '${val}:${typeof val}' is returned`, () => val); - }); + } }); diff --git a/packages/diff-sequences/__benchmarks__/test.js b/packages/diff-sequences/__benchmarks__/test.js index 317a5a8849bc..0fdc66032a69 100644 --- a/packages/diff-sequences/__benchmarks__/test.js +++ b/packages/diff-sequences/__benchmarks__/test.js @@ -142,13 +142,13 @@ const testLength = n => { writeHeading3(n); - [2, 4, 8].forEach(tenth => { + for (const tenth of [2, 4, 8]) { testDeleteInsert( tenth, all, getItems(n, i => i % 10 >= tenth && `${i}`), ); - }); + } testChange( 1, all, diff --git a/packages/expect-utils/src/__tests__/utils.test.ts b/packages/expect-utils/src/__tests__/utils.test.ts index fd1e2c588ed5..ce95e208599d 100644 --- a/packages/expect-utils/src/__tests__/utils.test.ts +++ b/packages/expect-utils/src/__tests__/utils.test.ts @@ -118,7 +118,7 @@ describe('getPath()', () => { }); describe('getObjectSubset', () => { - [ + for (const [object, subset, expected] of [ [{a: 'b', c: 'd'}, {a: 'd'}, {a: 'b'}], [{a: [1, 2], b: 'b'}, {a: [3, 4]}, {a: [1, 2]}], [[{a: 'b', c: 'd'}], [{a: 'z'}], [{a: 'b'}]], @@ -129,7 +129,7 @@ describe('getObjectSubset', () => { ], [{a: [1]}, {a: [1, 2]}, {a: [1]}], [new Date('2015-11-30'), new Date('2016-12-30'), new Date('2015-11-30')], - ].forEach(([object, subset, expected]) => { + ]) { test( `expect(getObjectSubset(${stringify(object)}, ${stringify(subset)}))` + `.toEqual(${stringify(expected)})`, @@ -137,7 +137,7 @@ describe('getObjectSubset', () => { expect(getObjectSubset(object, subset)).toEqual(expected); }, ); - }); + } describe('returns the object instance if the subset has no extra properties', () => { test('Date', () => { diff --git a/packages/expect-utils/src/utils.ts b/packages/expect-utils/src/utils.ts index b1375c1d53b6..a68354c4882e 100644 --- a/packages/expect-utils/src/utils.ts +++ b/packages/expect-utils/src/utils.ts @@ -140,18 +140,18 @@ export const getObjectSubset = ( const trimmed: any = {}; seenReferences.set(object, trimmed); - getObjectKeys(object) - .filter(key => hasPropertyInObject(subset, key)) - .forEach(key => { - trimmed[key] = seenReferences.has(object[key]) - ? seenReferences.get(object[key]) - : getObjectSubset( - object[key], - subset[key], - customTesters, - seenReferences, - ); - }); + for (const key of getObjectKeys(object).filter(key => + hasPropertyInObject(subset, key), + )) { + trimmed[key] = seenReferences.has(object[key]) + ? seenReferences.get(object[key]) + : getObjectSubset( + object[key], + subset[key], + customTesters, + seenReferences, + ); + } if (getObjectKeys(trimmed).length > 0) { return trimmed; @@ -440,7 +440,7 @@ export const partition = ( ): [Array, Array] => { const result: [Array, Array] = [[], []]; - items.forEach(item => result[predicate(item) ? 0 : 1].push(item)); + for (const item of items) result[predicate(item) ? 0 : 1].push(item); return result; }; diff --git a/packages/expect/src/__tests__/asymmetricMatchers.test.ts b/packages/expect/src/__tests__/asymmetricMatchers.test.ts index 3fb5f90835ef..4e14bf39249d 100644 --- a/packages/expect/src/__tests__/asymmetricMatchers.test.ts +++ b/packages/expect/src/__tests__/asymmetricMatchers.test.ts @@ -25,7 +25,7 @@ import { test('Any.asymmetricMatch()', () => { class Thing {} - [ + for (const test of [ any(String).asymmetricMatch('jest'), any(Number).asymmetricMatch(1), any(Function).asymmetricMatch(() => {}), @@ -36,13 +36,13 @@ test('Any.asymmetricMatch()', () => { any(Object).asymmetricMatch(null), any(Array).asymmetricMatch([]), any(Thing).asymmetricMatch(new Thing()), - ].forEach(test => { + ]) { jestExpect(test).toBe(true); - }); + } }); test('Any.asymmetricMatch() on primitive wrapper classes', () => { - [ + for (const test of [ // eslint-disable-next-line no-new-wrappers any(String).asymmetricMatch(new String('jest')), // eslint-disable-next-line no-new-wrappers @@ -53,9 +53,9 @@ test('Any.asymmetricMatch() on primitive wrapper classes', () => { any(Boolean).asymmetricMatch(new Boolean(true)), any(BigInt).asymmetricMatch(Object(1n)), any(Symbol).asymmetricMatch(Object(Symbol())), - ].forEach(test => { + ]) { jestExpect(test).toBe(true); - }); + } }); test('Any.toAsymmetricMatcher()', () => { @@ -63,7 +63,7 @@ test('Any.toAsymmetricMatcher()', () => { }); test('Any.toAsymmetricMatcher() with function name', () => { - [ + for (const [name, fn] of [ ['someFunc', function someFunc() {}], ['$someFunc', function $someFunc() {}], [ @@ -98,9 +98,9 @@ test('Any.toAsymmetricMatcher() with function name', () => { return $someFuncWithFakeToString; })(), ], - ].forEach(([name, fn]) => { + ]) { jestExpect(any(fn).toAsymmetricMatcher()).toBe(`Any<${name}>`); - }); + } }); test('Any throws when called with empty constructor', () => { @@ -111,25 +111,25 @@ test('Any throws when called with empty constructor', () => { }); test('Anything matches any type', () => { - [ + for (const test of [ anything().asymmetricMatch('jest'), anything().asymmetricMatch(1), anything().asymmetricMatch(() => {}), anything().asymmetricMatch(true), anything().asymmetricMatch({}), anything().asymmetricMatch([]), - ].forEach(test => { + ]) { jestExpect(test).toBe(true); - }); + } }); test('Anything does not match null and undefined', () => { - [ + for (const test of [ anything().asymmetricMatch(null), anything().asymmetricMatch(undefined), - ].forEach(test => { + ]) { jestExpect(test).toBe(false); - }); + } }); test('Anything.toAsymmetricMatcher()', () => { @@ -137,14 +137,14 @@ test('Anything.toAsymmetricMatcher()', () => { }); test('ArrayContaining matches', () => { - [ + for (const test of [ arrayContaining([]).asymmetricMatch('jest'), arrayContaining(['foo']).asymmetricMatch(['foo']), arrayContaining(['foo']).asymmetricMatch(['foo', 'bar']), arrayContaining([]).asymmetricMatch({}), - ].forEach(test => { + ]) { jestExpect(test).toEqual(true); - }); + } }); test('ArrayContaining does not match', () => { @@ -163,14 +163,14 @@ test('ArrayNotContaining matches', () => { }); test('ArrayNotContaining does not match', () => { - [ + for (const test of [ arrayNotContaining([]).asymmetricMatch('jest'), arrayNotContaining(['foo']).asymmetricMatch(['foo']), arrayNotContaining(['foo']).asymmetricMatch(['foo', 'bar']), arrayNotContaining([]).asymmetricMatch({}), - ].forEach(test => { + ]) { jestExpect(test).toEqual(false); - }); + } }); test('ArrayNotContaining throws for non-arrays', () => { @@ -182,7 +182,7 @@ test('ArrayNotContaining throws for non-arrays', () => { test('ObjectContaining matches', () => { const foo = Symbol('foo'); - [ + for (const test of [ objectContaining({}).asymmetricMatch('jest'), objectContaining({foo: 'foo'}).asymmetricMatch({foo: 'foo', jest: 'jest'}), objectContaining({foo: undefined}).asymmetricMatch({foo: undefined}), @@ -194,15 +194,15 @@ test('ObjectContaining matches', () => { jest: 'jest', }), objectContaining({[foo]: 'foo'}).asymmetricMatch({[foo]: 'foo'}), - ].forEach(test => { + ]) { jestExpect(test).toEqual(true); - }); + } }); test('ObjectContaining does not match', () => { const foo = Symbol('foo'); const bar = Symbol('bar'); - [ + for (const test of [ objectContaining({foo: 'foo'}).asymmetricMatch({bar: 'bar'}), objectContaining({foo: 'foo'}).asymmetricMatch({foo: 'foox'}), objectContaining({foo: undefined}).asymmetricMatch({}), @@ -211,9 +211,9 @@ test('ObjectContaining does not match', () => { foo: {bar: 'baz', foobar: 'qux'}, }).asymmetricMatch({foo: {bar: 'baz'}}), objectContaining({[foo]: 'foo'}).asymmetricMatch({[bar]: 'bar'}), - ].forEach(test => { + ]) { jestExpect(test).toEqual(false); - }); + } }); test('ObjectContaining matches defined properties', () => { @@ -257,7 +257,7 @@ test('ObjectContaining does not mutate the sample', () => { test('ObjectNotContaining matches', () => { const foo = Symbol('foo'); const bar = Symbol('bar'); - [ + for (const test of [ objectContaining({}).asymmetricMatch(null), objectContaining({}).asymmetricMatch(undefined), objectNotContaining({[foo]: 'foo'}).asymmetricMatch({[bar]: 'bar'}), @@ -276,13 +276,13 @@ test('ObjectNotContaining matches', () => { objectNotContaining({foo: 'foo', jest: 'jest'}).asymmetricMatch({ foo: 'foo', }), - ].forEach(test => { + ]) { jestExpect(test).toEqual(true); - }); + } }); test('ObjectNotContaining does not match', () => { - [ + for (const test of [ objectNotContaining({}).asymmetricMatch('jest'), objectNotContaining({foo: 'foo'}).asymmetricMatch({ foo: 'foo', @@ -298,29 +298,27 @@ test('ObjectNotContaining does not match', () => { objectNotContaining({}).asymmetricMatch(null), objectNotContaining({}).asymmetricMatch(undefined), objectNotContaining({}).asymmetricMatch({}), - ].forEach(test => { + ]) { jestExpect(test).toEqual(false); - }); + } }); test('ObjectNotContaining inverts ObjectContaining', () => { - ( - [ - [{}, null], - [{foo: 'foo'}, {foo: 'foo', jest: 'jest'}], - [{foo: 'foo', jest: 'jest'}, {foo: 'foo'}], - [{foo: undefined}, {foo: undefined}], - [{foo: undefined}, {}], - [{first: {second: {}}}, {first: {second: {}}}], - [{first: objectContaining({second: {}})}, {first: {second: {}}}], - [{first: objectNotContaining({second: {}})}, {first: {second: {}}}], - [{}, {foo: undefined}], - ] as const - ).forEach(([sample, received]) => { + for (const [sample, received] of [ + [{}, null], + [{foo: 'foo'}, {foo: 'foo', jest: 'jest'}], + [{foo: 'foo', jest: 'jest'}, {foo: 'foo'}], + [{foo: undefined}, {foo: undefined}], + [{foo: undefined}, {}], + [{first: {second: {}}}, {first: {second: {}}}], + [{first: objectContaining({second: {}})}, {first: {second: {}}}], + [{first: objectNotContaining({second: {}})}, {first: {second: {}}}], + [{}, {foo: undefined}], + ] as const) { jestExpect(objectNotContaining(sample).asymmetricMatch(received)).toEqual( !objectContaining(sample).asymmetricMatch(received), ); - }); + } }); test('ObjectNotContaining throws for non-objects', () => { @@ -411,7 +409,7 @@ test('StringNotMatching returns true if received value is not string', () => { }); describe('closeTo', () => { - [ + for (const [expected, received] of [ [0, 0], [0, 0.001], [1.23, 1.229], @@ -420,37 +418,37 @@ describe('closeTo', () => { [1.23, 1.234], [Infinity, Infinity], [-Infinity, -Infinity], - ].forEach(([expected, received]) => { + ]) { test(`${expected} closeTo ${received} return true`, () => { jestExpect(closeTo(expected).asymmetricMatch(received)).toBe(true); }); test(`${expected} notCloseTo ${received} return false`, () => { jestExpect(notCloseTo(expected).asymmetricMatch(received)).toBe(false); }); - }); + } - [ + for (const [expected, received] of [ [0, 0.01], [1, 1.23], [1.23, 1.2249999], [Infinity, -Infinity], [Infinity, 1.23], [-Infinity, -1.23], - ].forEach(([expected, received]) => { + ]) { test(`${expected} closeTo ${received} return false`, () => { jestExpect(closeTo(expected).asymmetricMatch(received)).toBe(false); }); test(`${expected} notCloseTo ${received} return true`, () => { jestExpect(notCloseTo(expected).asymmetricMatch(received)).toBe(true); }); - }); + } - [ + for (const [expected, received, precision] of [ [0, 0.1, 0], [0, 0.0001, 3], [0, 0.000004, 5], [2.0000002, 2, 5], - ].forEach(([expected, received, precision]) => { + ]) { test(`${expected} closeTo ${received} with precision ${precision} return true`, () => { jestExpect(closeTo(expected, precision).asymmetricMatch(received)).toBe( true, @@ -461,12 +459,12 @@ describe('closeTo', () => { notCloseTo(expected, precision).asymmetricMatch(received), ).toBe(false); }); - }); + } - [ + for (const [expected, received, precision] of [ [3.141592e-7, 3e-7, 8], [56789, 51234, -4], - ].forEach(([expected, received, precision]) => { + ]) { test(`${expected} closeTo ${received} with precision ${precision} return false`, () => { jestExpect(closeTo(expected, precision).asymmetricMatch(received)).toBe( false, @@ -477,7 +475,7 @@ describe('closeTo', () => { notCloseTo(expected, precision).asymmetricMatch(received), ).toBe(true); }); - }); + } test('closeTo throw if expected is not number', () => { jestExpect(() => { diff --git a/packages/expect/src/__tests__/matchers.test.js b/packages/expect/src/__tests__/matchers.test.js index 8bee39142ea5..c932e8647d51 100644 --- a/packages/expect/src/__tests__/matchers.test.js +++ b/packages/expect/src/__tests__/matchers.test.js @@ -66,7 +66,7 @@ describe('.rejects', () => { }).rejects.toThrow('Test'); }); - ['a', [1], () => {}, {a: 1}].forEach(value => { + for (const value of ['a', [1], () => {}, {a: 1}]) { it(`fails non-promise value ${stringify(value)} synchronously`, () => { let error; try { @@ -87,9 +87,9 @@ describe('.rejects', () => { expect(error).toBeDefined(); expect(error.message).toMatchSnapshot(); }); - }); + } - [4, null, true, undefined].forEach(value => { + for (const value of [4, null, true, undefined]) { it(`fails non-promise value ${stringify(value)} synchronously`, () => { let error; try { @@ -110,7 +110,7 @@ describe('.rejects', () => { expect(error).toBeDefined(); expect(error.message).toMatchSnapshot(); }); - }); + } it('fails for promise that resolves', async () => { let error; @@ -143,7 +143,7 @@ describe('.resolves', () => { ).resolves.toThrow(); }); - ['a', [1], () => {}, {a: 1}].forEach(value => { + for (const value of ['a', [1], () => {}, {a: 1}]) { it(`fails non-promise value ${stringify(value)} synchronously`, () => { let error; try { @@ -165,9 +165,9 @@ describe('.resolves', () => { expect(error).toBeDefined(); expect(error.message).toMatchSnapshot(); }); - }); + } - [4, null, true, undefined].forEach(value => { + for (const value of [4, null, true, undefined]) { it(`fails non-promise value ${stringify(value)} synchronously`, () => { let error; try { @@ -189,7 +189,7 @@ describe('.resolves', () => { expect(error).toBeDefined(); expect(error.message).toMatchSnapshot(); }); - }); + } it('fails for promise that rejects', async () => { let error; @@ -218,7 +218,7 @@ describe('.toBe()', () => { jestExpect(BigInt(1)).toBe(BigInt(1)); }); - [ + for (const [a, b] of [ [1, 2], [true, false], [() => {}, () => {}], @@ -243,32 +243,32 @@ describe('.toBe()', () => { [[], []], [null, undefined], [-0, +0], - ].forEach(([a, b]) => { + ]) { it(`fails for: ${stringify(a)} and ${stringify(b)}`, () => { expect(() => jestExpect(a).toBe(b)).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [a, b] of [ [BigInt(1), BigInt(2)], [{a: BigInt(1)}, {a: BigInt(1)}], - ].forEach(([a, b]) => { + ]) { it(`fails for: ${stringify(a)} and ${stringify(b)}`, () => { expect(() => jestExpect(a).toBe(b)).toThrow('toBe'); }); - }); + } - [false, 1, 'a', undefined, null, {}, []].forEach(v => { + for (const v of [false, 1, 'a', undefined, null, {}, []]) { it(`fails for '${stringify(v)}' with '.not'`, () => { expect(() => jestExpect(v).not.toBe(v)).toThrowErrorMatchingSnapshot(); }); - }); + } - [BigInt(1), BigInt('1')].forEach(v => { + for (const v of [BigInt(1), BigInt('1')]) { it(`fails for '${stringify(v)}' with '.not'`, () => { expect(() => jestExpect(v).not.toBe(v)).toThrow('toBe'); }); - }); + } it('does not crash on circular references', () => { const obj = {}; @@ -487,7 +487,7 @@ describe('.toStrictEqual()', () => { describe('.toEqual()', () => { /* eslint-disable no-new-wrappers */ - [ + for (const [a, b] of [ [true, false], [1, 2], [0, -0], @@ -683,28 +683,28 @@ describe('.toEqual()', () => { Object.assign([], {[Symbol()]: 1}), Object.assign([], {[Symbol()]: 1}), // issue 11056: also check symbols ], - ].forEach(([a, b]) => { + ]) { test(`{pass: false} expect(${stringify(a)}).toEqual(${stringify( b, )})`, () => { expect(() => jestExpect(a).toEqual(b)).toThrowErrorMatchingSnapshot(); jestExpect(a).not.toEqual(b); }); - }); + } - [ + for (const [a, b] of [ [BigInt(1), BigInt(2)], [BigInt(1), 1], - ].forEach(([a, b]) => { + ]) { test(`{pass: false} expect(${stringify(a)}).toEqual(${stringify( b, )})`, () => { expect(() => jestExpect(a).toEqual(b)).toThrow('toEqual'); jestExpect(a).not.toEqual(b); }); - }); + } - [ + for (const [a, b] of [ [true, true], [1, 1], [NaN, NaN], @@ -928,16 +928,16 @@ describe('.toEqual()', () => { [{a: 1, b: jestExpect.optionalFn()}, {a: 1}], [[1], [1, jestExpect.optionalFn()]], [[1, jestExpect.optionalFn()], [1]], - ].forEach(([a, b]) => { + ]) { test(`{pass: true} expect(${stringify(a)}).not.toEqual(${stringify( b, )})`, () => { jestExpect(a).toEqual(b); expect(() => jestExpect(a).not.toEqual(b)).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [a, b] of [ [BigInt(1), BigInt(1)], [BigInt(0), BigInt('0')], [[BigInt(1)], [BigInt(1)]], @@ -948,14 +948,14 @@ describe('.toEqual()', () => { [Immutable.List([BigInt(1)]), Immutable.List([BigInt(1)])], [{a: BigInt(99)}, {a: BigInt(99)}], [new Set([BigInt(1), BigInt(2)]), new Set([BigInt(1), BigInt(2)])], - ].forEach(([a, b]) => { + ]) { test(`{pass: true} expect(${stringify(a)}).not.toEqual(${stringify( b, )})`, () => { jestExpect(a).toEqual(b); expect(() => jestExpect(a).not.toEqual(b)).toThrow('toEqual'); }); - }); + } test('assertion error matcherResult property contains matcher name, expected and actual values', () => { const actual = {a: 1}; @@ -1092,7 +1092,7 @@ describe('.toBeInstanceOf()', () => { }); class SubHasNameProp extends DefinesNameProp {} - [ + for (const [a, b] of [ [new Map(), Map], [[], Array], [new A(), A], @@ -1101,7 +1101,7 @@ describe('.toBeInstanceOf()', () => { [new SubHasNameProp(), DefinesNameProp], // omit extends [new SubHasStaticNameMethod(), B], // Received [new HasStaticNameMethod(), HasStaticNameMethod], // Expected - ].forEach(([a, b]) => { + ]) { test(`passing ${stringify(a)} and ${stringify(b)}`, () => { expect(() => jestExpect(a).not.toBeInstanceOf(b), @@ -1109,9 +1109,9 @@ describe('.toBeInstanceOf()', () => { jestExpect(a).toBeInstanceOf(b); }); - }); + } - [ + for (const [a, b] of [ ['a', String], [1, Number], [true, Boolean], @@ -1121,7 +1121,7 @@ describe('.toBeInstanceOf()', () => { [null, String], [/\w+/, function () {}], [new DefinesNameProp(), RegExp], - ].forEach(([a, b]) => { + ]) { test(`failing ${stringify(a)} and ${stringify(b)}`, () => { expect(() => jestExpect(a).toBeInstanceOf(b), @@ -1129,7 +1129,7 @@ describe('.toBeInstanceOf()', () => { jestExpect(a).not.toBeInstanceOf(b); }); - }); + } it('throws if constructor is not a function', () => { expect(() => @@ -1147,7 +1147,7 @@ describe('.toBeTruthy(), .toBeFalsy()', () => { ).toThrowErrorMatchingSnapshot(); }); - [{}, [], true, 1, 'a', 0.5, new Map(), () => {}, Infinity].forEach(v => { + for (const v of [{}, [], true, 1, 'a', 0.5, new Map(), () => {}, Infinity]) { test(`'${stringify(v)}' is truthy`, () => { jestExpect(v).toBeTruthy(); jestExpect(v).not.toBeFalsy(); @@ -1158,9 +1158,9 @@ describe('.toBeTruthy(), .toBeFalsy()', () => { expect(() => jestExpect(v).toBeFalsy()).toThrowErrorMatchingSnapshot(); }); - }); + } - [BigInt(1)].forEach(v => { + for (const v of [BigInt(1)]) { test(`'${stringify(v)}' is truthy`, () => { jestExpect(v).toBeTruthy(); jestExpect(v).not.toBeFalsy(); @@ -1169,9 +1169,9 @@ describe('.toBeTruthy(), .toBeFalsy()', () => { expect(() => jestExpect(v).toBeFalsy()).toThrow('toBeFalsy'); }); - }); + } - [false, null, NaN, 0, '', undefined].forEach(v => { + for (const v of [false, null, NaN, 0, '', undefined]) { test(`'${stringify(v)}' is falsy`, () => { jestExpect(v).toBeFalsy(); jestExpect(v).not.toBeTruthy(); @@ -1182,9 +1182,9 @@ describe('.toBeTruthy(), .toBeFalsy()', () => { jestExpect(v).not.toBeFalsy(), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [BigInt(0)].forEach(v => { + for (const v of [BigInt(0)]) { test(`'${stringify(v)}' is falsy`, () => { jestExpect(v).toBeFalsy(); jestExpect(v).not.toBeTruthy(); @@ -1193,35 +1193,46 @@ describe('.toBeTruthy(), .toBeFalsy()', () => { expect(() => jestExpect(v).not.toBeFalsy()).toThrow('toBeFalsy'); }); - }); + } }); describe('.toBeNaN()', () => { it('{pass: true} expect(NaN).toBeNaN()', () => { - [NaN, Math.sqrt(-1), Infinity - Infinity, 0 / 0].forEach(v => { + for (const v of [NaN, Math.sqrt(-1), Infinity - Infinity, 0 / 0]) { jestExpect(v).toBeNaN(); expect(() => jestExpect(v).not.toBeNaN()).toThrowErrorMatchingSnapshot(); - }); + } }); it('throws', () => { - [1, '', null, undefined, {}, [], 0.2, 0, Infinity, -Infinity].forEach(v => { + for (const v of [ + 1, + '', + null, + undefined, + {}, + [], + 0.2, + 0, + Infinity, + -Infinity, + ]) { expect(() => jestExpect(v).toBeNaN()).toThrowErrorMatchingSnapshot(); jestExpect(v).not.toBeNaN(); - }); + } }); }); describe('.toBeNull()', () => { - [{}, [], true, 1, 'a', 0.5, new Map(), () => {}, Infinity].forEach(v => { + for (const v of [{}, [], true, 1, 'a', 0.5, new Map(), () => {}, Infinity]) { test(`fails for '${stringify(v)}'`, () => { jestExpect(v).not.toBeNull(); expect(() => jestExpect(v).toBeNull()).toThrowErrorMatchingSnapshot(); }); - }); + } it('fails for null with .not', () => { expect(() => @@ -1235,7 +1246,7 @@ describe('.toBeNull()', () => { }); describe('.toBeDefined(), .toBeUndefined()', () => { - [{}, [], true, 1, 'a', 0.5, new Map(), () => {}, Infinity].forEach(v => { + for (const v of [{}, [], true, 1, 'a', 0.5, new Map(), () => {}, Infinity]) { test(`'${stringify(v)}' is defined`, () => { jestExpect(v).toBeDefined(); jestExpect(v).not.toBeUndefined(); @@ -1248,9 +1259,9 @@ describe('.toBeDefined(), .toBeUndefined()', () => { jestExpect(v).toBeUndefined(), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [BigInt(1)].forEach(v => { + for (const v of [BigInt(1)]) { test(`'${stringify(v)}' is defined`, () => { jestExpect(v).toBeDefined(); jestExpect(v).not.toBeUndefined(); @@ -1259,7 +1270,7 @@ describe('.toBeDefined(), .toBeUndefined()', () => { expect(() => jestExpect(v).toBeUndefined()).toThrow('toBeUndefined'); }); - }); + } test('undefined is undefined', () => { jestExpect(undefined).toBeUndefined(); @@ -1279,7 +1290,7 @@ describe( '.toBeGreaterThan(), .toBeLessThan(), ' + '.toBeGreaterThanOrEqual(), .toBeLessThanOrEqual()', () => { - [ + for (const [small, big] of [ [1, 2], [-Infinity, Infinity], [Number.MIN_VALUE, Number.MAX_VALUE], @@ -1287,7 +1298,7 @@ describe( [0b11, 0b111], [0o11, 0o22], [0.1, 0.2], - ].forEach(([small, big]) => { + ]) { it(`{pass: true} expect(${small}).toBeLessThan(${big})`, () => { jestExpect(small).toBeLessThan(big); }); @@ -1353,7 +1364,7 @@ describe( jestExpect(big).toBeLessThanOrEqual(small), ).toThrowErrorMatchingSnapshot(); }); - }); + } test('can compare BigInt to Numbers', () => { const a = BigInt(2); @@ -1363,11 +1374,11 @@ describe( jestExpect(a).toBeLessThan(3); jestExpect(a).toBeLessThanOrEqual(2); }); - [ + for (const [small, big] of [ [BigInt(1), BigInt(2)], [BigInt(0x11), BigInt(0x22)], [-1, BigInt(2)], - ].forEach(([small, big]) => { + ]) { it(`{pass: true} expect(${stringify(small)}).toBeLessThan(${stringify( big, )})`, () => { @@ -1449,15 +1460,15 @@ describe( 'toBeLessThanOrEqual', ); }); - }); + } - [ + for (const [n1, n2] of [ [1, 1], [Number.MIN_VALUE, Number.MIN_VALUE], [Number.MAX_VALUE, Number.MAX_VALUE], [Infinity, Infinity], [-Infinity, -Infinity], - ].forEach(([n1, n2]) => { + ]) { test(`equal numbers: [${n1}, ${n2}]`, () => { jestExpect(n1).toBeGreaterThanOrEqual(n2); jestExpect(n1).toBeLessThanOrEqual(n2); @@ -1470,12 +1481,12 @@ describe( jestExpect(n1).not.toBeLessThanOrEqual(n2), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [n1, n2] of [ [BigInt(1), BigInt(1)], [BigInt(Number.MAX_SAFE_INTEGER), BigInt(Number.MAX_SAFE_INTEGER)], - ].forEach(([n1, n2]) => { + ]) { test(`equal numbers: [${n1}, ${n2}]`, () => { jestExpect(n1).toBeGreaterThanOrEqual(n2); jestExpect(n1).toBeLessThanOrEqual(n2); @@ -1488,7 +1499,7 @@ describe( 'toBeLessThanOrEqual', ); }); - }); + } }, ); @@ -1516,7 +1527,7 @@ describe('.toContain(), .toContainEqual()', () => { ); }); - [ + for (const [list, v] of [ [[1, 2, 3, 4], 1], [['a', 'b', 'c', 'd'], 'a'], [[undefined, null], null], @@ -1526,7 +1537,7 @@ describe('.toContain(), .toContainEqual()', () => { ['11112111', '2'], [new Set(['abc', 'def']), 'abc'], [typedArray, 1], - ].forEach(([list, v]) => { + ]) { it(`'${stringify(list)}' contains '${stringify(v)}'`, () => { jestExpect(list).toContain(v); @@ -1534,25 +1545,25 @@ describe('.toContain(), .toContainEqual()', () => { jestExpect(list).not.toContain(v), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [list, v] of [ [[BigInt(1), BigInt(2), BigInt(3), BigInt(4)], BigInt(1)], [[1, 2, 3, BigInt(3), 4], BigInt(3)], - ].forEach(([list, v]) => { + ]) { it(`'${stringify(list)}' contains '${stringify(v)}'`, () => { jestExpect(list).toContain(v); expect(() => jestExpect(list).not.toContain(v)).toThrow('toContain'); }); - }); + } - [ + for (const [list, v] of [ [[1, 2, 3], 4], [[null, undefined], 1], [[{}, []], []], [[{}, []], {}], - ].forEach(([list, v]) => { + ]) { it(`'${stringify(list)}' does not contain '${stringify(v)}'`, () => { jestExpect(list).not.toContain(v); @@ -1560,15 +1571,15 @@ describe('.toContain(), .toContainEqual()', () => { jestExpect(list).toContain(v), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [[[BigInt(1), BigInt(2), BigInt(3)], 3]].forEach(([list, v]) => { + for (const [list, v] of [[[BigInt(1), BigInt(2), BigInt(3)], 3]]) { it(`'${stringify(list)}' does not contain '${stringify(v)}'`, () => { jestExpect(list).not.toContain(v); expect(() => jestExpect(list).toContain(v)).toThrow('toContain'); }); - }); + } test('error cases', () => { expect(() => jestExpect(null).toContain(1)).toThrowErrorMatchingSnapshot(); @@ -1585,7 +1596,7 @@ describe('.toContain(), .toContainEqual()', () => { expect(() => jestExpect('1').toContain(BigInt(1))).toThrow('toContain'); }); - [ + for (const [list, v] of [ [[1, 2, 3, 4], 1], [['a', 'b', 'c', 'd'], 'a'], [[undefined, null], null], @@ -1594,7 +1605,7 @@ describe('.toContain(), .toContainEqual()', () => { [[{a: 'b'}, {a: 'c'}], {a: 'b'}], [new Set([1, 2, 3, 4]), 1], [typedArray, 1], - ].forEach(([list, v]) => { + ]) { it(`'${stringify(list)}' contains a value equal to '${stringify( v, )}'`, () => { @@ -1603,9 +1614,9 @@ describe('.toContain(), .toContainEqual()', () => { jestExpect(list).not.toContainEqual(v), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [[[{a: 'b'}, {a: 'c'}], {a: 'd'}]].forEach(([list, v]) => { + for (const [list, v] of [[[{a: 'b'}, {a: 'c'}], {a: 'd'}]]) { it(`'${stringify(list)}' does not contain a value equal to'${stringify( v, )}'`, () => { @@ -1615,7 +1626,7 @@ describe('.toContain(), .toContainEqual()', () => { jestExpect(list).toContainEqual(v), ).toThrowErrorMatchingSnapshot(); }); - }); + } test('error cases for toContainEqual', () => { expect(() => @@ -1625,7 +1636,7 @@ describe('.toContain(), .toContainEqual()', () => { }); describe('.toBeCloseTo', () => { - [ + for (const [n1, n2] of [ [0, 0], [0, 0.001], [1.23, 1.229], @@ -1634,7 +1645,7 @@ describe('.toBeCloseTo', () => { [1.23, 1.234], [Infinity, Infinity], [-Infinity, -Infinity], - ].forEach(([n1, n2]) => { + ]) { it(`{pass: true} expect(${n1}).toBeCloseTo(${n2})`, () => { jestExpect(n1).toBeCloseTo(n2); @@ -1642,16 +1653,16 @@ describe('.toBeCloseTo', () => { jestExpect(n1).not.toBeCloseTo(n2), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [n1, n2] of [ [0, 0.01], [1, 1.23], [1.23, 1.2249999], [Infinity, -Infinity], [Infinity, 1.23], [-Infinity, -1.23], - ].forEach(([n1, n2]) => { + ]) { it(`{pass: false} expect(${n1}).toBeCloseTo(${n2})`, () => { jestExpect(n1).not.toBeCloseTo(n2); @@ -1659,12 +1670,12 @@ describe('.toBeCloseTo', () => { jestExpect(n1).toBeCloseTo(n2), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [n1, n2, p] of [ [3.141592e-7, 3e-7, 8], [56789, 51234, -4], - ].forEach(([n1, n2, p]) => { + ]) { it(`{pass: false} expect(${n1}).toBeCloseTo(${n2}, ${p})`, () => { jestExpect(n1).not.toBeCloseTo(n2, p); @@ -1672,14 +1683,14 @@ describe('.toBeCloseTo', () => { jestExpect(n1).toBeCloseTo(n2, p), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [n1, n2, p] of [ [0, 0.1, 0], [0, 0.0001, 3], [0, 0.000004, 5], [2.0000002, 2, 5], - ].forEach(([n1, n2, p]) => { + ]) { it(`{pass: true} expect(${n1}).toBeCloseTo(${n2}, ${p})`, () => { jestExpect(n1).toBeCloseTo(n2, p); @@ -1687,7 +1698,7 @@ describe('.toBeCloseTo', () => { jestExpect(n1).not.toBeCloseTo(n2, p), ).toThrowErrorMatchingSnapshot(); }); - }); + } describe('throws: Matcher error', () => { test('promise empty isNot false received', () => { @@ -1744,10 +1755,10 @@ describe('.toBeCloseTo', () => { }); describe('.toMatch()', () => { - [ + for (const [n1, n2] of [ ['foo', 'foo'], ['Foo bar', /^foo/i], - ].forEach(([n1, n2]) => { + ]) { it(`{pass: true} expect(${n1}).toMatch(${n2})`, () => { jestExpect(n1).toMatch(n2); @@ -1755,18 +1766,18 @@ describe('.toMatch()', () => { jestExpect(n1).not.toMatch(n2), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [n1, n2] of [ ['bar', 'foo'], ['bar', /foo/], - ].forEach(([n1, n2]) => { + ]) { it(`throws: [${n1}, ${n2}]`, () => { expect(() => jestExpect(n1).toMatch(n2)).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [n1, n2] of [ [1, 'foo'], [{}, 'foo'], [[], 'foo'], @@ -1774,7 +1785,7 @@ describe('.toMatch()', () => { [/foo/i, 'foo'], [() => {}, 'foo'], [undefined, 'foo'], - ].forEach(([n1, n2]) => { + ]) { it( 'throws if non String actual value passed:' + ` [${stringify(n1)}, ${stringify(n2)}]`, @@ -1782,16 +1793,16 @@ describe('.toMatch()', () => { expect(() => jestExpect(n1).toMatch(n2)).toThrowErrorMatchingSnapshot(); }, ); - }); + } - [ + for (const [n1, n2] of [ ['foo', 1], ['foo', {}], ['foo', []], ['foo', true], ['foo', () => {}], ['foo', undefined], - ].forEach(([n1, n2]) => { + ]) { it( 'throws if non String/RegExp expected value passed:' + ` [${stringify(n1)}, ${stringify(n2)}]`, @@ -1799,7 +1810,7 @@ describe('.toMatch()', () => { expect(() => jestExpect(n1).toMatch(n2)).toThrowErrorMatchingSnapshot(); }, ); - }); + } it('escapes strings properly', () => { jestExpect('this?: throws').toMatch('this?: throws'); @@ -1814,14 +1825,14 @@ describe('.toMatch()', () => { }); describe('.toHaveLength', () => { - [ + for (const [received, length] of [ [[1, 2], 2], [[], 0], [['a', 'b'], 2], ['abc', 3], ['', 0], [() => {}, 0], - ].forEach(([received, length]) => { + ]) { test(`{pass: true} expect(${stringify( received, )}).toHaveLength(${length})`, () => { @@ -1830,15 +1841,15 @@ describe('.toHaveLength', () => { jestExpect(received).not.toHaveLength(length), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [received, length] of [ [[1, 2], 3], [[], 1], [['a', 'b'], 99], ['abc', 66], ['', 1], - ].forEach(([received, length]) => { + ]) { test(`{pass: false} expect(${stringify( received, )}).toHaveLength(${length})`, () => { @@ -1847,7 +1858,7 @@ describe('.toHaveLength', () => { jestExpect(received).toHaveLength(length), ).toThrowErrorMatchingSnapshot(); }); - }); + } test('error cases', () => { expect(() => @@ -1951,7 +1962,7 @@ describe('.toHaveProperty()', () => { const valueDiffMultiple = 'Roses are red, violets are blue.\nTesting with Jest\nIs good for you.'; - [ + for (const [obj, keyPath, value] of [ [{a: {b: {c: {d: 1}}}}, 'a.b.c.d', 1], [{a: {b: {c: {d: 1}}}}, ['a', 'b', 'c', 'd'], 1], [{'a.b.c.d': 1}, ['a.b.c.d'], 1], @@ -1974,7 +1985,7 @@ describe('.toHaveProperty()', () => { ['', 'length', 0], [memoized, 'memo', []], [{'': 1}, '', 1], - ].forEach(([obj, keyPath, value]) => { + ]) { test(`{pass: true} expect(${stringify( obj, )}).toHaveProperty('${keyPath}', ${stringify(value)})`, () => { @@ -1983,9 +1994,9 @@ describe('.toHaveProperty()', () => { jestExpect(obj).not.toHaveProperty(keyPath, value), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [obj, keyPath, value] of [ [{a: {b: {c: {d: 1}}}}, 'a.b.ttt.d', 1], [{a: {b: {c: {d: 1}}}}, 'a.b.c.d', 2], [{'a.b.c.d': 1}, 'a.b.c.d', 2], @@ -2003,7 +2014,7 @@ describe('.toHaveProperty()', () => { [new Foo(), 'a', 'a'], [new Foo(), 'b', undefined], [{a: {}}, 'a.b', undefined], - ].forEach(([obj, keyPath, value]) => { + ]) { test(`{pass: false} expect(${stringify( obj, )}).toHaveProperty('${keyPath}', ${stringify(value)})`, () => { @@ -2012,16 +2023,16 @@ describe('.toHaveProperty()', () => { ).toThrowErrorMatchingSnapshot(); jestExpect(obj).not.toHaveProperty(keyPath, value); }); - }); + } - [ + for (const [obj, keyPath] of [ [{a: {b: {c: {d: 1}}}}, 'a.b.c.d'], [{a: {b: {c: {d: 1}}}}, ['a', 'b', 'c', 'd']], [{'a.b.c.d': 1}, ['a.b.c.d']], [{a: {b: [1, 2, 3]}}, ['a', 'b', 1]], [{a: 0}, 'a'], [{a: {b: undefined}}, 'a.b'], - ].forEach(([obj, keyPath]) => { + ]) { test(`{pass: true} expect(${stringify( obj, )}).toHaveProperty('${keyPath}')`, () => { @@ -2030,9 +2041,9 @@ describe('.toHaveProperty()', () => { jestExpect(obj).not.toHaveProperty(keyPath), ).toThrowErrorMatchingSnapshot(); }); - }); + } - [ + for (const [obj, keyPath] of [ [{a: {b: {c: {}}}}, 'a.b.c.d'], [{a: {b: {c: {}}}}, '.a.b.c'], [{a: 1}, 'a.b.c.d'], @@ -2044,7 +2055,7 @@ describe('.toHaveProperty()', () => { ['', 'key'], [Symbol(), 'key'], [Object.assign(Object.create(null), {key: 1}), 'not'], - ].forEach(([obj, keyPath]) => { + ]) { test(`{pass: false} expect(${stringify( obj, )}).toHaveProperty('${keyPath}')`, () => { @@ -2053,16 +2064,16 @@ describe('.toHaveProperty()', () => { ).toThrowErrorMatchingSnapshot(); jestExpect(obj).not.toHaveProperty(keyPath); }); - }); + } - [ + for (const [obj, keyPath] of [ [null, 'a.b'], [undefined, 'a'], [{a: {b: {}}}, undefined], [{a: {b: {}}}, null], [{a: {b: {}}}, 1], [{}, []], // Residue: pass must be initialized - ].forEach(([obj, keyPath]) => { + ]) { test(`{error} expect(${stringify( obj, )}).toHaveProperty('${keyPath}')`, () => { @@ -2070,7 +2081,7 @@ describe('.toHaveProperty()', () => { jestExpect(obj).toHaveProperty(keyPath), ).toThrowErrorMatchingSnapshot(); }); - }); + } }); describe('toMatchObject()', () => { @@ -2100,7 +2111,7 @@ describe('toMatchObject()', () => { }; const testNotToMatchSnapshots = tuples => { - tuples.forEach(([n1, n2]) => { + for (const [n1, n2] of tuples) { it(`{pass: true} expect(${stringify(n1)}).toMatchObject(${stringify( n2, )})`, () => { @@ -2109,11 +2120,11 @@ describe('toMatchObject()', () => { jestExpect(n1).not.toMatchObject(n2), ).toThrowErrorMatchingSnapshot(); }); - }); + } }; const testToMatchSnapshots = tuples => { - tuples.forEach(([n1, n2]) => { + for (const [n1, n2] of tuples) { it(`{pass: false} expect(${stringify(n1)}).toMatchObject(${stringify( n2, )})`, () => { @@ -2122,7 +2133,7 @@ describe('toMatchObject()', () => { jestExpect(n1).toMatchObject(n2), ).toThrowErrorMatchingSnapshot(); }); - }); + } }; describe('circular references', () => { @@ -2279,7 +2290,7 @@ describe('toMatchObject()', () => { [{a: 'b'}, {toString: jestExpect.any(Function)}], ]); - [ + for (const [n1, n2] of [ [null, {}], [4, {}], ['44', {}], @@ -2290,7 +2301,7 @@ describe('toMatchObject()', () => { [{}, 'some string'], [{}, true], [{}, undefined], - ].forEach(([n1, n2]) => { + ]) { it(`throws expect(${stringify(n1)}).toMatchObject(${stringify( n2, )})`, () => { @@ -2298,7 +2309,7 @@ describe('toMatchObject()', () => { jestExpect(n1).toMatchObject(n2), ).toThrowErrorMatchingSnapshot(); }); - }); + } it('does not match properties up in the prototype chain', () => { const a = {}; diff --git a/packages/expect/src/__tests__/spyMatchers.test.ts b/packages/expect/src/__tests__/spyMatchers.test.ts index f344c74eb102..69a23ab507bd 100644 --- a/packages/expect/src/__tests__/spyMatchers.test.ts +++ b/packages/expect/src/__tests__/spyMatchers.test.ts @@ -106,24 +106,24 @@ describe.each(['toBeCalledTimes', 'toHaveBeenCalledTimes'] as const)( fn(); jestExpect(fn)[calledTimes](1); - [{}, [], true, 'a', new Map(), () => {}].forEach(value => { + for (const value of [{}, [], true, 'a', new Map(), () => {}]) { expect(() => // @ts-expect-error: Testing runtime error jestExpect(fn)[calledTimes](value), ).toThrowErrorMatchingSnapshot(); - }); + } }); test('.not only accepts a number argument', () => { const fn = jest.fn(); jestExpect(fn).not[calledTimes](1); - [{}, [], true, 'a', new Map(), () => {}].forEach(value => { + for (const value of [{}, [], true, 'a', new Map(), () => {}]) { expect(() => // @ts-expect-error: Testing runtime error jestExpect(fn).not[calledTimes](value), ).toThrowErrorMatchingSnapshot(); - }); + } }); test('passes if function called equal to expected times', () => { @@ -824,24 +824,24 @@ describe.each(['toReturnTimes', 'toHaveReturnedTimes'] as const)( fn(); jestExpect(fn)[returnedTimes](1); - [{}, [], true, 'a', new Map(), () => {}].forEach(value => { + for (const value of [{}, [], true, 'a', new Map(), () => {}]) { expect(() => // @ts-expect-error: Testing runtime error jestExpect(fn)[returnedTimes](value), ).toThrowErrorMatchingSnapshot(); - }); + } }); test('.not only accepts a number argument', () => { const fn = jest.fn(() => 42); jestExpect(fn).not[returnedTimes](2); - [{}, [], true, 'a', new Map(), () => {}].forEach(value => { + for (const value of [{}, [], true, 'a', new Map(), () => {}]) { expect(() => // @ts-expect-error: Testing runtime error jestExpect(fn).not[returnedTimes](value), ).toThrowErrorMatchingSnapshot(); - }); + } }); test('passes if function returned equal to expected times', () => { diff --git a/packages/expect/src/index.ts b/packages/expect/src/index.ts index 6b80867dbd7b..0bc82f2e41e7 100644 --- a/packages/expect/src/index.ts +++ b/packages/expect/src/index.ts @@ -113,7 +113,7 @@ export const expect: Expect = (actual: any, ...rest: Array) => { const err = new JestAssertionError(); - Object.keys(allMatchers).forEach(name => { + for (const name of Object.keys(allMatchers)) { const matcher = allMatchers[name]; const promiseMatcher = getPromiseMatcher(name, matcher) || matcher; expectation[name] = makeThrowingMatcher(matcher, false, '', actual); @@ -148,7 +148,7 @@ export const expect: Expect = (actual: any, ...rest: Array) => { actual, err, ); - }); + } return expectation; }; diff --git a/packages/expect/src/jestMatchersObject.ts b/packages/expect/src/jestMatchersObject.ts index a61e904a9b31..dcfe800729ef 100644 --- a/packages/expect/src/jestMatchersObject.ts +++ b/packages/expect/src/jestMatchersObject.ts @@ -58,7 +58,7 @@ export const setMatchers = ( isInternal: boolean, expect: Expect, ): void => { - Object.keys(matchers).forEach(key => { + for (const key of Object.keys(matchers)) { const matcher = matchers[key]; if (typeof matcher !== 'function') { @@ -121,7 +121,7 @@ export const setMatchers = ( writable: true, }); } - }); + } Object.assign((globalThis as any)[JEST_MATCHERS_OBJECT].matchers, matchers); }; diff --git a/packages/jest-circus/src/eventHandler.ts b/packages/jest-circus/src/eventHandler.ts index 8a7e2403e52b..448a5395efb6 100644 --- a/packages/jest-circus/src/eventHandler.ts +++ b/packages/jest-circus/src/eventHandler.ts @@ -53,10 +53,10 @@ const eventHandler: Circus.EventHandler = (event, state) => { invariant(currentDescribeBlock, 'currentDescribeBlock must be there'); if (!describeBlockHasTests(currentDescribeBlock)) { - currentDescribeBlock.hooks.forEach(hook => { + for (const hook of currentDescribeBlock.hooks) { hook.asyncError.message = `Invalid: ${hook.type}() may not be used in a describe block containing no tests.`; state.unhandledErrors.push(hook.asyncError); - }); + } } // pass mode of currentDescribeBlock to tests @@ -68,11 +68,11 @@ const eventHandler: Circus.EventHandler = (event, state) => { ) ); if (shouldPassMode) { - currentDescribeBlock.children.forEach(child => { + for (const child of currentDescribeBlock.children) { if (child.type === 'test' && !child.mode) { child.mode = currentDescribeBlock.mode; } - }); + } } if ( !state.hasFocusedTests && diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts index 5be34097c451..e6f89603b91c 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts @@ -108,13 +108,13 @@ const _addSnapshotData = ( results: TestResult, snapshotState: SnapshotState, ) => { - results.testResults.forEach(({fullName, status}) => { + for (const {fullName, status} of results.testResults) { if (status === 'pending' || status === 'failed') { // if test is skipped or failed, we don't want to mark // its snapshots as obsolete. snapshotState.markSnapshotsAsCheckedForTest(fullName); } - }); + } const uncheckedCount = snapshotState.getUncheckedCount(); const uncheckedKeys = snapshotState.getUncheckedKeys(); diff --git a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts index 01c121317d97..a69a04066b8a 100644 --- a/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts +++ b/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts @@ -108,10 +108,8 @@ export const initialize = async ({ // Jest tests snapshotSerializers in order preceding built-in serializers. // Therefore, add in reverse because the last added is the first tested. - config.snapshotSerializers - .concat() - .reverse() - .forEach(path => addSerializer(localRequire(path))); + for (const path of config.snapshotSerializers.concat().reverse()) + addSerializer(localRequire(path)); const snapshotResolver = await buildSnapshotResolver(config, localRequire); const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath); diff --git a/packages/jest-circus/src/utils.ts b/packages/jest-circus/src/utils.ts index 931f28adb64d..47147e261700 100644 --- a/packages/jest-circus/src/utils.ts +++ b/packages/jest-circus/src/utils.ts @@ -355,7 +355,7 @@ export const makeSingleTestResult = ( const stackLine = stackLines[1]; let parsedLine = stackUtils.parseLine(stackLine); if (parsedLine?.file?.startsWith(jestEachBuildDir)) { - const stackLine = stackLines[4]; + const stackLine = stackLines[2]; parsedLine = stackUtils.parseLine(stackLine); } if ( diff --git a/packages/jest-config/src/__mocks__/fs.js b/packages/jest-config/src/__mocks__/fs.js index 3cb5a003651b..b268ae3d50cf 100644 --- a/packages/jest-config/src/__mocks__/fs.js +++ b/packages/jest-config/src/__mocks__/fs.js @@ -12,9 +12,9 @@ const fs = jest.createMockFromModule('fs'); const mockFiles = new Map(); function __setMockFiles(newMockFiles) { mockFiles.clear(); - Object.keys(newMockFiles).forEach(fileName => { + for (const fileName of Object.keys(newMockFiles)) { mockFiles.set(fileName, newMockFiles[fileName]); - }); + } } fs.__setMockFiles = __setMockFiles; diff --git a/packages/jest-config/src/__mocks__/read-pkg.js b/packages/jest-config/src/__mocks__/read-pkg.js index f6c87708f7ee..77f339b7cbc2 100644 --- a/packages/jest-config/src/__mocks__/read-pkg.js +++ b/packages/jest-config/src/__mocks__/read-pkg.js @@ -10,9 +10,9 @@ const mockFiles = new Map(); function __setMockFiles(newMockFiles) { mockFiles.clear(); - Object.keys(newMockFiles).forEach(fileName => { + for (const fileName of Object.keys(newMockFiles)) { mockFiles.set(fileName, newMockFiles[fileName]); - }); + } } function readPkg(file) { diff --git a/packages/jest-config/src/normalize.ts b/packages/jest-config/src/normalize.ts index 60e7de2945dd..23bcf4a1f089 100644 --- a/packages/jest-config/src/normalize.ts +++ b/packages/jest-config/src/normalize.ts @@ -216,7 +216,7 @@ const setupBabelJest = (options: Config.InitialOptionsWithRootDir) => { return regex.test('a.ts') || regex.test('a.tsx'); }); - [customJSPattern, customTSPattern].forEach(pattern => { + for (const pattern of [customJSPattern, customTSPattern]) { if (pattern) { const customTransformer = transform[pattern]; if (Array.isArray(customTransformer)) { @@ -235,7 +235,7 @@ const setupBabelJest = (options: Config.InitialOptionsWithRootDir) => { } } } - }); + } } else { babelJest = require.resolve('babel-jest'); options.transform = { @@ -981,9 +981,9 @@ export default async function normalize( ); } - newOptions.roots.forEach((root, i) => { + for (const [i, root] of newOptions.roots.entries()) { verifyDirectoryExists(root, `roots[${i}]`); - }); + } try { // try to resolve windows short paths, ignoring errors (permission errors, mostly) diff --git a/packages/jest-core/src/SearchSource.ts b/packages/jest-core/src/SearchSource.ts index 7c83ba570139..b9227587868b 100644 --- a/packages/jest-core/src/SearchSource.ts +++ b/packages/jest-core/src/SearchSource.ts @@ -196,14 +196,14 @@ export default class SearchSource { const collectCoverageFrom = new Set(); - testModulesMap.forEach(testModule => { + for (const testModule of testModulesMap) { if (!testModule.dependencies) { - return; + continue; } - testModule.dependencies.forEach(p => { + for (const p of testModule.dependencies) { if (!allPathsAbsolute.includes(p)) { - return; + continue; } const filename = replaceRootDirInPath(this._context.config.rootDir, p); @@ -212,8 +212,8 @@ export default class SearchSource { ? path.relative(this._context.config.rootDir, filename) : filename, ); - }); - }); + } + } return { collectCoverageFrom, @@ -362,14 +362,14 @@ export default class SearchSource { const {changedFiles} = changedFilesInfo; const dependencyResolver = await this._getOrBuildDependencyResolver(); const relatedSourcesSet = new Set(); - changedFiles.forEach(filePath => { + for (const filePath of changedFiles) { if (this.isTestFilePath(filePath)) { const sourcePaths = dependencyResolver.resolve(filePath, { skipNodeResolution: this._context.config.skipNodeResolution, }); - sourcePaths.forEach(sourcePath => relatedSourcesSet.add(sourcePath)); + for (const sourcePath of sourcePaths) relatedSourcesSet.add(sourcePath); } - }); + } return Array.from(relatedSourcesSet); } } diff --git a/packages/jest-core/src/TestScheduler.ts b/packages/jest-core/src/TestScheduler.ts index 77caa9a95c3f..9ab4429c9160 100644 --- a/packages/jest-core/src/TestScheduler.ts +++ b/packages/jest-core/src/TestScheduler.ts @@ -98,12 +98,12 @@ class TestScheduler { ); const timings: Array = []; const testContexts = new Set(); - tests.forEach(test => { + for (const test of tests) { testContexts.add(test.context); if (test.duration) { timings.push(test.duration); } - }); + } const aggregatedResults = createAggregatedResults(tests.length); const estimatedTime = Math.ceil( @@ -180,7 +180,7 @@ class TestScheduler { ), ); - contextsWithSnapshotResolvers.forEach(([context, snapshotResolver]) => { + for (const [context, snapshotResolver] of contextsWithSnapshotResolvers) { const status = cleanupSnapshots( context.hasteFS, this._globalConfig.updateSnapshot, @@ -192,7 +192,7 @@ class TestScheduler { aggregatedResults.snapshot.filesRemovedList = ( aggregatedResults.snapshot.filesRemovedList || [] ).concat(status.filesRemovedList); - }); + } const updateAll = this._globalConfig.updateSnapshot === 'all'; aggregatedResults.snapshot.didUpdate = updateAll; aggregatedResults.snapshot.failure = !!( @@ -275,7 +275,7 @@ class TestScheduler { await testRunner.runTests(tests, watcher, testRunnerOptions); - unsubscribes.forEach(sub => sub()); + for (const sub of unsubscribes) sub(); } else { await testRunner.runTests( tests, diff --git a/packages/jest-core/src/__tests__/watch.test.js b/packages/jest-core/src/__tests__/watch.test.js index 8bd334bd91a4..f8988d256c95 100644 --- a/packages/jest-core/src/__tests__/watch.test.js +++ b/packages/jest-core/src/__tests__/watch.test.js @@ -875,7 +875,7 @@ describe('Watch mode flows', () => { runJestMock.mockReset(); stdin.emit('t'); - ['t', 'e', 's', 't'].forEach(key => stdin.emit(key)); + for (const key of ['t', 'e', 's', 't']) stdin.emit(key); stdin.emit(KEYS.ENTER); await nextTick(); @@ -893,7 +893,7 @@ describe('Watch mode flows', () => { runJestMock.mockReset(); stdin.emit('p'); - ['f', 'i', 'l', 'e'].forEach(key => stdin.emit(key)); + for (const key of ['f', 'i', 'l', 'e']) stdin.emit(key); stdin.emit(KEYS.ENTER); await nextTick(); @@ -911,12 +911,12 @@ describe('Watch mode flows', () => { runJestMock.mockReset(); stdin.emit('p'); - ['f', 'i', 'l', 'e'].forEach(key => stdin.emit(key)); + for (const key of ['f', 'i', 'l', 'e']) stdin.emit(key); stdin.emit(KEYS.ENTER); await nextTick(); stdin.emit('t'); - ['t', 'e', 's', 't'].forEach(key => stdin.emit(key)); + for (const key of ['t', 'e', 's', 't']) stdin.emit(key); stdin.emit(KEYS.ENTER); await nextTick(); @@ -1012,6 +1012,6 @@ class MockStdin { } emit(key) { - this._callbacks.forEach(cb => cb(key)); + for (const cb of this._callbacks) cb(key); } } diff --git a/packages/jest-core/src/__tests__/watchFileChanges.test.ts b/packages/jest-core/src/__tests__/watchFileChanges.test.ts index 4a50bcacf26b..ea3f8a6a3e22 100644 --- a/packages/jest-core/src/__tests__/watchFileChanges.test.ts +++ b/packages/jest-core/src/__tests__/watchFileChanges.test.ts @@ -182,6 +182,6 @@ class MockStdin { } emit(key: string) { - this._callbacks.forEach(cb => cb(key)); + for (const cb of this._callbacks) cb(key); } } diff --git a/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js b/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js index 0823be059280..9d84afe3c8df 100644 --- a/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js +++ b/packages/jest-core/src/__tests__/watchFilenamePatternMode.test.js @@ -102,11 +102,12 @@ describe('Watch mode flows', () => { }; // Write a pattern - ['p', '.', '*', '1', '0'].forEach(assertPattern); + for (const pattern of ['p', '.', '*', '1', '0']) assertPattern(pattern); - [KEYS.BACKSPACE, KEYS.BACKSPACE].forEach(assertPattern); + for (const pattern of [KEYS.BACKSPACE, KEYS.BACKSPACE]) + assertPattern(pattern); - ['3'].forEach(assertPattern); + for (const pattern of ['3']) assertPattern(pattern); // Runs Jest again runJestMock.mockReset(); @@ -124,15 +125,13 @@ describe('Watch mode flows', () => { stdin.emit('p'); await nextTick(); - ['p', '.', '*', '1', '0'] - - .concat(KEYS.ENTER) - .forEach(key => stdin.emit(key)); + for (const key of ['p', '.', '*', '1', '0'].concat(KEYS.ENTER)) + stdin.emit(key); stdin.emit('t'); await nextTick(); - ['t', 'e', 's', 't'].concat(KEYS.ENTER).forEach(key => stdin.emit(key)); + for (const key of ['t', 'e', 's', 't'].concat(KEYS.ENTER)) stdin.emit(key); await nextTick(); @@ -163,6 +162,6 @@ class MockStdin { } emit(key) { - this._callbacks.forEach(cb => cb(key)); + for (const cb of this._callbacks) cb(key); } } diff --git a/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js b/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js index c2a7f6d6c9e1..c07e78f65d38 100644 --- a/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js +++ b/packages/jest-core/src/__tests__/watchTestNamePatternMode.test.js @@ -116,11 +116,13 @@ describe('Watch mode flows', () => { }; // Write a pattern - ['c', 'o', 'n', ' ', '1', '2'].forEach(assertPattern); + for (const pattern of ['c', 'o', 'n', ' ', '1', '2']) + assertPattern(pattern); - [KEYS.BACKSPACE, KEYS.BACKSPACE].forEach(assertPattern); + for (const pattern of [KEYS.BACKSPACE, KEYS.BACKSPACE]) + assertPattern(pattern); - ['*'].forEach(assertPattern); + for (const pattern of ['*']) assertPattern(pattern); // Runs Jest again runJestMock.mockReset(); @@ -153,6 +155,6 @@ class MockStdin { } emit(key) { - this._callbacks.forEach(cb => cb(key)); + for (const cb of this._callbacks) cb(key); } } diff --git a/packages/jest-core/src/cli/index.ts b/packages/jest-core/src/cli/index.ts index 3cbea529ff1c..ecf754f227d1 100644 --- a/packages/jest-core/src/cli/index.ts +++ b/packages/jest-core/src/cli/index.ts @@ -65,12 +65,13 @@ export async function runCLI( if (argv.clearCache) { // stick in a Set to dedupe the deletions - new Set(configs.map(config => config.cacheDirectory)).forEach( - cacheDirectory => { - fs.rmSync(cacheDirectory, {force: true, recursive: true}); - process.stdout.write(`Cleared ${cacheDirectory}\n`); - }, + const uniqueConfigDirectories = new Set( + configs.map(config => config.cacheDirectory), ); + for (const cacheDirectory of uniqueConfigDirectories) { + fs.rmSync(cacheDirectory, {force: true, recursive: true}); + process.stdout.write(`Cleared ${cacheDirectory}\n`); + } exit(0); } diff --git a/packages/jest-core/src/plugins/FailedTestsInteractive.ts b/packages/jest-core/src/plugins/FailedTestsInteractive.ts index 08985b8faf63..39dd8756e8c8 100644 --- a/packages/jest-core/src/plugins/FailedTestsInteractive.ts +++ b/packages/jest-core/src/plugins/FailedTestsInteractive.ts @@ -84,16 +84,16 @@ export default class FailedTestsInteractivePlugin extends BaseWatchPlugin { return failedTestPaths; } - results.testResults.forEach(testResult => { - testResult.testResults.forEach(result => { + for (const testResult of results.testResults) { + for (const result of testResult.testResults) { if (result.status === 'failed') { failedTestPaths.push({ fullName: result.fullName, path: testResult.testFilePath, }); } - }); - }); + } + } return failedTestPaths; } diff --git a/packages/jest-core/src/plugins/UpdateSnapshotsInteractive.ts b/packages/jest-core/src/plugins/UpdateSnapshotsInteractive.ts index 7315f4125ad3..25c8d3516cd9 100644 --- a/packages/jest-core/src/plugins/UpdateSnapshotsInteractive.ts +++ b/packages/jest-core/src/plugins/UpdateSnapshotsInteractive.ts @@ -26,18 +26,18 @@ class UpdateSnapshotInteractivePlugin extends BaseWatchPlugin { return failedTestPaths; } - testResults.testResults.forEach(testResult => { + for (const testResult of testResults.testResults) { if (testResult.snapshot && testResult.snapshot.unmatched) { - testResult.testResults.forEach(result => { + for (const result of testResult.testResults) { if (result.status === 'failed') { failedTestPaths.push({ fullName: result.fullName, path: testResult.testFilePath, }); } - }); + } } - }); + } return failedTestPaths; } diff --git a/packages/jest-core/src/watch.ts b/packages/jest-core/src/watch.ts index 2c9502cd03e1..9237d5a78220 100644 --- a/packages/jest-core/src/watch.ts +++ b/packages/jest-core/src/watch.ts @@ -156,12 +156,12 @@ export default async function watch( const watchPlugins: Array = INTERNAL_PLUGINS.map( InternalPlugin => new InternalPlugin({stdin, stdout: outputStream}), ); - watchPlugins.forEach((plugin: WatchPlugin) => { + for (const plugin of watchPlugins) { const hookSubscriber = hooks.getSubscriber(); if (plugin.apply) { plugin.apply(hookSubscriber); } - }); + } if (globalConfig.watchPlugins != null) { const watchPluginKeys: WatchPluginKeysMap = new Map(); @@ -237,7 +237,7 @@ export default async function watch( emitFileChange(); - hasteMapInstances.forEach((hasteMapInstance, index) => { + for (const [index, hasteMapInstance] of hasteMapInstances.entries()) { hasteMapInstance.on('change', ({eventsQueue, hasteFS, moduleMap}) => { const validPaths = eventsQueue.filter(({filePath}) => isValidPath(globalConfig, filePath), @@ -260,7 +260,7 @@ export default async function watch( startRun(globalConfig); } }); - }); + } if (!hasExitListener) { hasExitListener = true; diff --git a/packages/jest-diff/src/__tests__/diff.test.ts b/packages/jest-diff/src/__tests__/diff.test.ts index 0493190626c0..7a4eedaebacb 100644 --- a/packages/jest-diff/src/__tests__/diff.test.ts +++ b/packages/jest-diff/src/__tests__/diff.test.ts @@ -47,13 +47,13 @@ const elementSymbol = Symbol.for('react.element'); expect.addSnapshotSerializer(alignedAnsiStyleSerializer); describe('different types', () => { - [ + for (const values of [ [1, 'a', 'number', 'string'], [{}, 'a', 'object', 'string'], [[], 2, 'array', 'number'], [null, undefined, 'null', 'undefined'], [() => {}, 3, 'function', 'number'], - ].forEach(values => { + ]) { const a = values[0]; const b = values[1]; const typeA = values[2]; @@ -65,11 +65,11 @@ describe('different types', () => { `Expected ${String(typeA)} but received ${String(typeB)}.`, ); }); - }); + } }); describe('no visual difference', () => { - [ + for (const values of [ ['a', 'a'], [{}, {}], [[], []], @@ -86,13 +86,13 @@ describe('no visual difference', () => { [false, false], [{a: 1}, {a: 1}], [{a: {b: 5}}, {a: {b: 5}}], - ].forEach(values => { + ]) { test(`'${JSON.stringify(values[0])}' and '${JSON.stringify( values[1], )}'`, () => { expect(stripped(values[0], values[1])).toBe(NO_DIFF_MESSAGE); }); - }); + } test('Map key order should be irrelevant', () => { const arg1 = new Map([ diff --git a/packages/jest-diff/src/diffLines.ts b/packages/jest-diff/src/diffLines.ts index 302445472da0..becd5b712cbb 100644 --- a/packages/jest-diff/src/diffLines.ts +++ b/packages/jest-diff/src/diffLines.ts @@ -26,7 +26,7 @@ const countChanges = (diffs: Array): ChangeCounts => { let a = 0; let b = 0; - diffs.forEach(diff => { + for (const diff of diffs) { switch (diff[0]) { case DIFF_DELETE: a += 1; @@ -36,7 +36,7 @@ const countChanges = (diffs: Array): ChangeCounts => { b += 1; break; } - }); + } return {a, b}; }; @@ -139,7 +139,7 @@ export const diffLinesUnified2 = ( // Replace comparison lines with displayable lines. let aIndex = 0; let bIndex = 0; - diffs.forEach((diff: Diff) => { + for (const diff of diffs) { switch (diff[0]) { case DIFF_DELETE: diff[1] = aLinesDisplay[aIndex]; @@ -156,7 +156,7 @@ export const diffLinesUnified2 = ( aIndex += 1; bIndex += 1; } - }); + } return printDiffLines(diffs, normalizeDiffOptions(options)); }; diff --git a/packages/jest-diff/src/getAlignedDiffs.ts b/packages/jest-diff/src/getAlignedDiffs.ts index fbda1a3e6a0e..e810507ec337 100644 --- a/packages/jest-diff/src/getAlignedDiffs.ts +++ b/packages/jest-diff/src/getAlignedDiffs.ts @@ -82,7 +82,7 @@ class ChangeBuffer { if (string.includes('\n')) { const substrings = string.split('\n'); const iLast = substrings.length - 1; - substrings.forEach((substring, i) => { + for (const [i, substring] of substrings.entries()) { if (i < iLast) { // The first substring completes the current change line. // A middle substring is a change line. @@ -94,7 +94,7 @@ class ChangeBuffer { // the newline appended to the end of expected and received strings. this.pushSubstring(substring); } - }); + } } else { // Append non-multiline string to current change line. this.pushDiff(diff); @@ -153,7 +153,7 @@ class CommonBuffer { if (string.includes('\n')) { const substrings = string.split('\n'); const iLast = substrings.length - 1; - substrings.forEach((substring, i) => { + for (const [i, substring] of substrings.entries()) { if (i === 0) { const subdiff = new Diff(op, substring); if ( @@ -179,7 +179,7 @@ class CommonBuffer { // the newline appended to the end of expected and received strings. this.pushDiffChangeLines(new Diff(op, substring)); } - }); + } } else { // Append non-multiline string to current change lines. // Important: It cannot be at the end following empty change lines, @@ -213,7 +213,7 @@ const getAlignedDiffs = ( const insertBuffer = new ChangeBuffer(DIFF_INSERT, changeColor); const commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); - diffs.forEach(diff => { + for (const diff of diffs) { switch (diff[0]) { case DIFF_DELETE: deleteBuffer.align(diff); @@ -226,7 +226,7 @@ const getAlignedDiffs = ( default: commonBuffer.align(diff); } - }); + } return commonBuffer.getLines(); }; diff --git a/packages/jest-each/src/__tests__/array.test.ts b/packages/jest-each/src/__tests__/array.test.ts index 444f7c367655..c6260836d132 100644 --- a/packages/jest-each/src/__tests__/array.test.ts +++ b/packages/jest-each/src/__tests__/array.test.ts @@ -39,7 +39,7 @@ const getGlobalTestMocks = () => { }; describe('jest-each', () => { - [ + for (const keyPath of [ ['test'], ['test', 'concurrent'], ['test', 'concurrent', 'only'], @@ -51,7 +51,7 @@ describe('jest-each', () => { ['describe'], ['fdescribe'], ['describe', 'only'], - ].forEach(keyPath => { + ]) { describe(`.${keyPath.join('.')}`, () => { test('throws an error when not called with an array', () => { const globalTestMocks = getGlobalTestMocks(); @@ -415,7 +415,7 @@ describe('jest-each', () => { ); }); }); - }); + } describe('done callback', () => { test.each([ @@ -459,7 +459,7 @@ describe('jest-each', () => { ); }); - [ + for (const keyPath of [ ['xtest'], ['test', 'skip'], ['test', 'concurrent', 'skip'], @@ -467,7 +467,7 @@ describe('jest-each', () => { ['it', 'skip'], ['xdescribe'], ['describe', 'skip'], - ].forEach(keyPath => { + ]) { describe(`.${keyPath.join('.')}`, () => { test('calls global with given title', () => { const globalTestMocks = getGlobalTestMocks(); @@ -551,5 +551,5 @@ describe('jest-each', () => { ); }); }); - }); + } }); diff --git a/packages/jest-each/src/__tests__/template.test.ts b/packages/jest-each/src/__tests__/template.test.ts index 161cb827bff8..0400fabbeb80 100644 --- a/packages/jest-each/src/__tests__/template.test.ts +++ b/packages/jest-each/src/__tests__/template.test.ts @@ -43,7 +43,7 @@ const getGlobalTestMocks = }; describe('jest-each', () => { - [ + for (const keyPath of [ ['test'], ['test', 'concurrent'], ['test', 'concurrent', 'only'], @@ -55,7 +55,7 @@ describe('jest-each', () => { ['describe'], ['fdescribe'], ['describe', 'only'], - ].forEach(keyPath => { + ]) { describe(`.${keyPath.join('.')}`, () => { test('throws error when there are additional words in first column heading', () => { const globalTestMocks = getGlobalTestMocks(); @@ -500,7 +500,7 @@ describe('jest-each', () => { ); }); }); - }); + } describe('done callback', () => { test.each([ @@ -551,7 +551,7 @@ describe('jest-each', () => { ); }); - [ + for (const keyPath of [ ['xtest'], ['test', 'skip'], ['test', 'concurrent'], @@ -560,7 +560,7 @@ describe('jest-each', () => { ['it', 'skip'], ['xdescribe'], ['describe', 'skip'], - ].forEach(keyPath => { + ]) { describe(`.${keyPath.join('.')}`, () => { test('calls global with given title', () => { const globalTestMocks = getGlobalTestMocks(); @@ -658,5 +658,5 @@ describe('jest-each', () => { ); }); }); - }); + } }); diff --git a/packages/jest-each/src/bind.ts b/packages/jest-each/src/bind.ts index a5112456717e..890ef103abf1 100644 --- a/packages/jest-each/src/bind.ts +++ b/packages/jest-each/src/bind.ts @@ -51,7 +51,7 @@ export default function bind( ? buildArrayTests(title, table) : buildTemplateTests(title, table, taggedTemplateData); - return tests.forEach(row => + for (const row of tests) { needsEachError ? cb( row.title, @@ -63,8 +63,10 @@ export default function bind( row.title, applyArguments(supportsDone, row.arguments, test), timeout, - ), - ); + ); + } + + return; } catch (e: any) { const err = new Error(e.message); err.stack = error.stack?.replace(/^Error: /s, `Error: ${e.message}`); diff --git a/packages/jest-environment-jsdom/src/__tests__/jsdom_environment.test.ts b/packages/jest-environment-jsdom/src/__tests__/jsdom_environment.test.ts index 138f37e32f8e..3b4d95f95b1d 100644 --- a/packages/jest-environment-jsdom/src/__tests__/jsdom_environment.test.ts +++ b/packages/jest-environment-jsdom/src/__tests__/jsdom_environment.test.ts @@ -23,9 +23,9 @@ describe('JSDomEnvironment', () => { const timer1 = env.global.setTimeout(() => {}, 0); const timer2 = env.global.setInterval(() => {}, 0); - [timer1, timer2].forEach(timer => { + for (const timer of [timer1, timer2]) { expect(typeof timer).toBe('number'); - }); + } }); it('has modern fake timers implementation', () => { diff --git a/packages/jest-environment-node/src/__tests__/node_environment.test.ts b/packages/jest-environment-node/src/__tests__/node_environment.test.ts index 7e4254ebbeea..bd29974e2b8f 100644 --- a/packages/jest-environment-node/src/__tests__/node_environment.test.ts +++ b/packages/jest-environment-node/src/__tests__/node_environment.test.ts @@ -65,11 +65,11 @@ describe('NodeEnvironment', () => { const timer1 = env1.global.setTimeout(() => {}, 0); const timer2 = env1.global.setInterval(() => {}, 0); - [timer1, timer2].forEach(timer => { + for (const timer of [timer1, timer2]) { expect(timer.id).toBeDefined(); expect(typeof timer.ref).toBe('function'); expect(typeof timer.unref).toBe('function'); - }); + } }); it('has modern fake timers implementation', () => { diff --git a/packages/jest-fake-timers/src/legacyFakeTimers.ts b/packages/jest-fake-timers/src/legacyFakeTimers.ts index 5aad100821ed..a7fdc011acf8 100644 --- a/packages/jest-fake-timers/src/legacyFakeTimers.ts +++ b/packages/jest-fake-timers/src/legacyFakeTimers.ts @@ -247,14 +247,14 @@ export default class FakeTimers { // See https://github.com/jestjs/jest/pull/4608 for details const timerEntries = Array.from(this._timers.entries()); this._checkFakeTimers(); - this._immediates.forEach(this._runImmediate, this); + for (const _immediate of this._immediates) this._runImmediate(_immediate); - timerEntries - .sort(([, left], [, right]) => left.expiry - right.expiry) - .forEach(([timerHandle, timer]) => { - this._now = timer.expiry; - this._runTimerHandle(timerHandle); - }); + for (const [timerHandle, timer] of timerEntries.sort( + ([, left], [, right]) => left.expiry - right.expiry, + )) { + this._now = timer.expiry; + this._runTimerHandle(timerHandle); + } } advanceTimersToNextTimer(steps = 1): void { @@ -579,12 +579,12 @@ export default class FakeTimers { let nextTimerHandle = null; let soonestTime = MS_IN_A_YEAR; - this._timers.forEach((timer, uuid) => { + for (const [uuid, timer] of this._timers.entries()) { if (timer.expiry < soonestTime) { soonestTime = timer.expiry; nextTimerHandle = uuid; } - }); + } if (nextTimerHandle === null) { return null; diff --git a/packages/jest-fake-timers/src/modernFakeTimers.ts b/packages/jest-fake-timers/src/modernFakeTimers.ts index c9db7ba331c0..3208697353a0 100644 --- a/packages/jest-fake-timers/src/modernFakeTimers.ts +++ b/packages/jest-fake-timers/src/modernFakeTimers.ts @@ -203,9 +203,10 @@ export default class FakeTimers { Object.keys(this._fakeTimers.timers) as Array, ); - fakeTimersConfig.doNotFake?.forEach(nameOfFakeableAPI => { - toFake.delete(nameOfFakeableAPI); - }); + if (fakeTimersConfig.doNotFake) + for (const nameOfFakeableAPI of fakeTimersConfig.doNotFake) { + toFake.delete(nameOfFakeableAPI); + } return { advanceTimeDelta, diff --git a/packages/jest-haste-map/src/crawlers/node.ts b/packages/jest-haste-map/src/crawlers/node.ts index 12ae165422ed..f9a50462dfa0 100644 --- a/packages/jest-haste-map/src/crawlers/node.ts +++ b/packages/jest-haste-map/src/crawlers/node.ts @@ -76,19 +76,19 @@ function find( } return; } - entries.forEach(entry => { + for (const entry of entries) { const file = path.join(directory, entry.name); if (ignore(file)) { - return; + continue; } if (entry.isSymbolicLink()) { - return; + continue; } if (entry.isDirectory()) { search(file); - return; + continue; } activeCalls++; @@ -115,7 +115,7 @@ function find( callback(result); } }); - }); + } if (activeCalls === 0) { callback(result); @@ -124,7 +124,7 @@ function find( } if (roots.length > 0) { - roots.forEach(search); + for (const root of roots) search(root); } else { callback(result); } @@ -147,13 +147,13 @@ function findNative( if (extensions.length > 0) { args.push('('); } - extensions.forEach((ext, index) => { + for (const [index, ext] of extensions.entries()) { if (index) { args.push('-o'); } args.push('-iname'); args.push(`*.${ext}`); - }); + } if (extensions.length > 0) { args.push(')'); } @@ -176,7 +176,7 @@ function findNative( const result: Result = []; let count = lines.length; if (count) { - lines.forEach(path => { + for (const path of lines) { fs.stat(path, (err, stat) => { // Filter out symlinks that describe directories if (!err && stat && !stat.isDirectory()) { @@ -186,7 +186,7 @@ function findNative( callback(result); } }); - }); + } } else { callback([]); } @@ -213,7 +213,7 @@ export async function nodeCrawl(options: CrawlerOptions): Promise<{ const callback = (list: Result) => { const files = new Map(); const removedFiles = new Map(data.files); - list.forEach(fileData => { + for (const fileData of list) { const [filePath, mtime, size] = fileData; const relativeFilePath = fastPath.relative(rootDir, filePath); const existingFile = data.files.get(relativeFilePath); @@ -224,7 +224,7 @@ export async function nodeCrawl(options: CrawlerOptions): Promise<{ files.set(relativeFilePath, ['', mtime, size, 0, '', null]); } removedFiles.delete(relativeFilePath); - }); + } data.files = files; resolve({ diff --git a/packages/jest-haste-map/src/watchers/NodeWatcher.js b/packages/jest-haste-map/src/watchers/NodeWatcher.js index 0168fe35ba9c..b1c58f17e4d5 100644 --- a/packages/jest-haste-map/src/watchers/NodeWatcher.js +++ b/packages/jest-haste-map/src/watchers/NodeWatcher.js @@ -193,7 +193,7 @@ module.exports = class NodeWatcher extends EventEmitter { */ close() { - Object.keys(this.watched).forEach(this.stopWatching, this); + for (const key of Object.keys(this.watched)) this.stopWatching(key); this.removeAllListeners(); return Promise.resolve(); @@ -218,6 +218,7 @@ module.exports = class NodeWatcher extends EventEmitter { let found = false; let closest = {mtime: 0}; let c = 0; + // eslint-disable-next-line unicorn/no-array-for-each Object.keys(this.dirRegistery[dir]).forEach(function (file, i, arr) { fs.lstat(path.join(dir, file), (error, stat) => { if (found) { diff --git a/packages/jest-haste-map/src/watchers/WatchmanWatcher.js b/packages/jest-haste-map/src/watchers/WatchmanWatcher.js index e068a8458cdf..b1a103b3c09d 100644 --- a/packages/jest-haste-map/src/watchers/WatchmanWatcher.js +++ b/packages/jest-haste-map/src/watchers/WatchmanWatcher.js @@ -195,7 +195,7 @@ WatchmanWatcher.prototype.handleChangeEvent = function (resp) { this.emit('fresh_instance'); } if (Array.isArray(resp.files)) { - resp.files.forEach(this.handleFileChange, this); + for (const file of resp.files) this.handleFileChange(file); } }; diff --git a/packages/jest-jasmine2/src/errorOnPrivate.ts b/packages/jest-jasmine2/src/errorOnPrivate.ts index ff839bb18a47..78c5a5d05de7 100644 --- a/packages/jest-jasmine2/src/errorOnPrivate.ts +++ b/packages/jest-jasmine2/src/errorOnPrivate.ts @@ -41,22 +41,22 @@ const disabledJasmineMethods: Record = { export function installErrorOnPrivate(global: Global.Global): void { const jasmine = global.jasmine; - (Object.keys(disabledGlobals) as Array).forEach( - functionName => { - global[functionName] = () => { - throwAtFunction(disabledGlobals[functionName], global[functionName]); - }; - }, - ); + for (const functionName of Object.keys( + disabledGlobals, + ) as Array) { + global[functionName] = () => { + throwAtFunction(disabledGlobals[functionName], global[functionName]); + }; + } - ( - Object.keys(disabledJasmineMethods) as Array - ).forEach(methodName => { + for (const methodName of Object.keys( + disabledJasmineMethods, + ) as Array) { // @ts-expect-error - void unallowd, but it throws 🤷 jasmine[methodName] = () => { throwAtFunction(disabledJasmineMethods[methodName], jasmine[methodName]); }; - }); + } function set() { throwAtFunction( diff --git a/packages/jest-jasmine2/src/index.ts b/packages/jest-jasmine2/src/index.ts index edbd92cb857f..09f575240981 100644 --- a/packages/jest-jasmine2/src/index.ts +++ b/packages/jest-jasmine2/src/index.ts @@ -8,7 +8,7 @@ import * as path from 'path'; import type {JestEnvironment} from '@jest/environment'; import {getCallsite} from '@jest/source-map'; -import type {AssertionResult, TestResult} from '@jest/test-result'; +import type {TestResult} from '@jest/test-result'; import type {Config, Global} from '@jest/types'; import type Runtime from 'jest-runtime'; import type {SnapshotState} from 'jest-snapshot'; @@ -62,7 +62,7 @@ export default async function jasmine2( const it = original(testName, fn, timeout); if (stack.getFileName()?.startsWith(jestEachBuildDir)) { - stack = getCallsite(4, sourcemaps); + stack = getCallsite(2, sourcemaps); } // @ts-expect-error: `it` is `void` for some reason it.result.__callsite = stack; @@ -204,13 +204,13 @@ export default async function jasmine2( } const addSnapshotData = (results: TestResult, snapshotState: SnapshotState) => { - results.testResults.forEach(({fullName, status}: AssertionResult) => { + for (const {fullName, status} of results.testResults) { if (status === 'pending' || status === 'failed') { // if test is skipped or failed, we don't want to mark // its snapshots as obsolete. snapshotState.markSnapshotsAsCheckedForTest(fullName); } - }); + } const uncheckedCount = snapshotState.getUncheckedCount(); const uncheckedKeys = snapshotState.getUncheckedKeys(); diff --git a/packages/jest-jasmine2/src/jasmine/Env.ts b/packages/jest-jasmine2/src/jasmine/Env.ts index 32ff7a1b54b0..d55698af5ca8 100644 --- a/packages/jest-jasmine2/src/jasmine/Env.ts +++ b/packages/jest-jasmine2/src/jasmine/Env.ts @@ -284,13 +284,13 @@ export default function jasmineEnv(j$: Jasmine) { j$.process.removeListener('unhandledRejection', uncaught); // restore previous exception handlers - oldListenersException.forEach(listener => { + for (const listener of oldListenersException) { j$.process.on('uncaughtException', listener); - }); + } - oldListenersRejection.forEach(listener => { + for (const listener of oldListenersRejection) { j$.process.on('unhandledRejection', listener); - }); + } }; this.execute = async function (runnablesToRun, suiteTree = topSuite) { diff --git a/packages/jest-jasmine2/src/jestExpect.ts b/packages/jest-jasmine2/src/jestExpect.ts index c1d15059d161..114b0bb9e398 100644 --- a/packages/jest-jasmine2/src/jestExpect.ts +++ b/packages/jest-jasmine2/src/jestExpect.ts @@ -26,7 +26,7 @@ export default function jestExpectAdapter(config: {expand: boolean}): void { jasmine.addMatchers = (jasmineMatchersObject: JasmineMatchersObject) => { const jestMatchersObject = Object.create(null); - Object.keys(jasmineMatchersObject).forEach(name => { + for (const name of Object.keys(jasmineMatchersObject)) { jestMatchersObject[name] = function (...args: Array) { // use "expect.extend" if you need to use equality testers (via this.equal) const result = jasmineMatchersObject[name](null, null); @@ -37,7 +37,7 @@ export default function jestExpectAdapter(config: {expand: boolean}): void { ? negativeCompare.apply(null, args) : result.compare.apply(null, args); }; - }); + } jestExpect.extend(jestMatchersObject); }; diff --git a/packages/jest-jasmine2/src/reporter.ts b/packages/jest-jasmine2/src/reporter.ts index f6c0e47bbc6f..179cde7cc7be 100644 --- a/packages/jest-jasmine2/src/reporter.ts +++ b/packages/jest-jasmine2/src/reporter.ts @@ -70,7 +70,7 @@ export default class Jasmine2Reporter implements Reporter { let numPendingTests = 0; let numTodoTests = 0; const testResults = this._testResults; - testResults.forEach(testResult => { + for (const testResult of testResults) { if (testResult.status === 'failed') { numFailingTests++; } else if (testResult.status === 'pending') { @@ -80,7 +80,7 @@ export default class Jasmine2Reporter implements Reporter { } else { numPassingTests++; } - }); + } const testResult = { ...createEmptyTestResult(), @@ -154,14 +154,14 @@ export default class Jasmine2Reporter implements Reporter { title: specResult.description, }; - specResult.failedExpectations.forEach(failed => { + for (const failed of specResult.failedExpectations) { const message = !failed.matcherName && typeof failed.stack === 'string' ? this._addMissingMessageToStack(failed.stack, failed.message) : failed.message || ''; results.failureMessages.push(message); results.failureDetails.push(failed); - }); + } return results; } diff --git a/packages/jest-jasmine2/src/setup_jest_globals.ts b/packages/jest-jasmine2/src/setup_jest_globals.ts index 15a04434515d..0f3aa696aebc 100644 --- a/packages/jest-jasmine2/src/setup_jest_globals.ts +++ b/packages/jest-jasmine2/src/setup_jest_globals.ts @@ -95,12 +95,9 @@ export default async function setupJestGlobals({ }: SetupOptions): Promise { // Jest tests snapshotSerializers in order preceding built-in serializers. // Therefore, add in reverse because the last added is the first tested. - config.snapshotSerializers - .concat() - .reverse() - .forEach(path => { - addSerializer(localRequire(path)); - }); + for (const path of config.snapshotSerializers.concat().reverse()) { + addSerializer(localRequire(path)); + } patchJasmine(); const {expand, updateSnapshot} = globalConfig; diff --git a/packages/jest-matcher-utils/src/Replaceable.ts b/packages/jest-matcher-utils/src/Replaceable.ts index 9eee1068c7e9..1044e1b9f28f 100644 --- a/packages/jest-matcher-utils/src/Replaceable.ts +++ b/packages/jest-matcher-utils/src/Replaceable.ts @@ -37,17 +37,17 @@ export default class Replaceable { forEach(cb: ReplaceableForEachCallBack): void { if (this.type === 'object') { const descriptors = Object.getOwnPropertyDescriptors(this.object); - [ + for (const key of [ ...Object.keys(descriptors), ...Object.getOwnPropertySymbols(descriptors), ] //@ts-expect-error because typescript do not support symbol key in object //https://github.com/microsoft/TypeScript/issues/1863 - .filter(key => descriptors[key].enumerable) - .forEach(key => { - cb(this.object[key], key, this.object); - }); + .filter(key => descriptors[key].enumerable)) { + cb(this.object[key], key, this.object); + } } else { + // eslint-disable-next-line unicorn/no-array-for-each this.object.forEach(cb); } } diff --git a/packages/jest-matcher-utils/src/__tests__/Replaceable.test.ts b/packages/jest-matcher-utils/src/__tests__/Replaceable.test.ts index cc3d48d0af55..a9fdc156c0cf 100644 --- a/packages/jest-matcher-utils/src/__tests__/Replaceable.test.ts +++ b/packages/jest-matcher-utils/src/__tests__/Replaceable.test.ts @@ -103,6 +103,7 @@ describe('Replaceable', () => { const object = {a: 1, b: 2, [symbolKey]: 3}; const replaceable = new Replaceable(object); const cb = jest.fn(); + // eslint-disable-next-line unicorn/no-array-for-each replaceable.forEach(cb); expect(cb).toHaveBeenCalledTimes(3); expect(cb.mock.calls[0]).toEqual([1, 'a', object]); @@ -113,6 +114,7 @@ describe('Replaceable', () => { test('array forEach', () => { const replaceable = new Replaceable([1, 2, 3]); const cb = jest.fn(); + // eslint-disable-next-line unicorn/no-array-for-each replaceable.forEach(cb); expect(cb).toHaveBeenCalledTimes(3); expect(cb.mock.calls[0]).toEqual([1, 0, [1, 2, 3]]); @@ -127,6 +129,7 @@ describe('Replaceable', () => { ]); const replaceable = new Replaceable(map); const cb = jest.fn(); + // eslint-disable-next-line unicorn/no-array-for-each replaceable.forEach(cb); expect(cb).toHaveBeenCalledTimes(2); expect(cb.mock.calls[0]).toEqual([1, 'a', map]); @@ -151,6 +154,7 @@ describe('Replaceable', () => { }); const replaceable = new Replaceable(object); const cb = jest.fn(); + // eslint-disable-next-line unicorn/no-array-for-each replaceable.forEach(cb); expect(cb).toHaveBeenCalledTimes(2); expect(cb.mock.calls[0]).toEqual([1, 'a', object]); diff --git a/packages/jest-matcher-utils/src/__tests__/index.test.ts b/packages/jest-matcher-utils/src/__tests__/index.test.ts index af8771c2cfd0..f1db019912f6 100644 --- a/packages/jest-matcher-utils/src/__tests__/index.test.ts +++ b/packages/jest-matcher-utils/src/__tests__/index.test.ts @@ -23,7 +23,7 @@ import { expect.addSnapshotSerializer(alignedAnsiStyleSerializer); describe('stringify()', () => { - [ + for (const [v, s] of [ [[], '[]'], [{}, '{}'], [1, '1'], @@ -39,11 +39,11 @@ describe('stringify()', () => { [/ab\.c/gi, '/ab\\.c/gi'], [BigInt(1), '1n'], [BigInt(0), '0n'], - ].forEach(([v, s]) => { + ]) { test(stringify(v), () => { expect(stringify(v)).toBe(s); }); - }); + } test('circular references', () => { const a: any = {}; @@ -231,7 +231,7 @@ jest.mock('jest-diff', () => ({ })); describe('diff', () => { test('forwards to jest-diff', () => { - [ + for (const [actual, expected] of [ ['a', 'b'], ['a', {}], ['a', null], @@ -240,9 +240,8 @@ describe('diff', () => { ['a', true], [1, true], [BigInt(1), true], - ].forEach(([actual, expected]) => - expect(diff(actual, expected)).toBe('diff output'), - ); + ]) + expect(diff(actual, expected)).toBe('diff output'); }); test('two booleans', () => { diff --git a/packages/jest-matcher-utils/src/deepCyclicCopyReplaceable.ts b/packages/jest-matcher-utils/src/deepCyclicCopyReplaceable.ts index 82cc0249a22c..64cca1335eda 100644 --- a/packages/jest-matcher-utils/src/deepCyclicCopyReplaceable.ts +++ b/packages/jest-matcher-utils/src/deepCyclicCopyReplaceable.ts @@ -125,9 +125,9 @@ function deepCyclicCopyMap( cycles.set(map, newMap); - map.forEach((value, key) => { + for (const [key, value] of map.entries()) { newMap.set(key, deepCyclicCopyReplaceable(value, cycles)); - }); + } return newMap as any; } diff --git a/packages/jest-matcher-utils/src/index.ts b/packages/jest-matcher-utils/src/index.ts index 665cff92539f..f1297b243c5a 100644 --- a/packages/jest-matcher-utils/src/index.ts +++ b/packages/jest-matcher-utils/src/index.ts @@ -444,6 +444,7 @@ function _replaceMatchedToAsymmetricMatcher( const expectedReplaceable = new Replaceable(replacedExpected); const receivedReplaceable = new Replaceable(replacedReceived); + // eslint-disable-next-line unicorn/no-array-for-each expectedReplaceable.forEach((expectedValue: unknown, key: unknown) => { const receivedValue = receivedReplaceable.get(key); if (isAsymmetricMatcher(expectedValue)) { diff --git a/packages/jest-message-util/src/index.ts b/packages/jest-message-util/src/index.ts index a91a0b5fef75..1d92371ef5a0 100644 --- a/packages/jest-message-util/src/index.ts +++ b/packages/jest-message-util/src/index.ts @@ -462,13 +462,13 @@ export const formatResultsErrors = ( ): string | null => { const failedResults: FailedResults = testResults.reduce( (errors, result) => { - result.failureMessages.forEach((item, index) => { + for (const [index, item] of result.failureMessages.entries()) { errors.push({ content: item, failureDetails: result.failureDetails[index], result, }); - }); + } return errors; }, [], diff --git a/packages/jest-mock/src/index.ts b/packages/jest-mock/src/index.ts index e58679739ded..32801248e668 100644 --- a/packages/jest-mock/src/index.ts +++ b/packages/jest-mock/src/index.ts @@ -686,7 +686,7 @@ export class ModuleMocker { finalReturnValue = (() => { if (this instanceof f) { // This is probably being called as a constructor - prototypeSlots.forEach(slot => { + for (const slot of prototypeSlots) { // Copy prototype methods to the instance to make // it easier to interact with mock instance call and // return values @@ -698,7 +698,7 @@ export class ModuleMocker { // @ts-expect-error no index signature this[slot]._protoImpl = protoImpl; } - }); + } // Run the mock constructor implementation const mockImpl = @@ -954,7 +954,7 @@ export class ModuleMocker { refs[metadata.refID] = mock; } - this._getSlots(metadata.members).forEach(slot => { + for (const slot of this._getSlots(metadata.members)) { const slotMetadata = (metadata.members && metadata.members[slot]) || {}; if (slotMetadata.ref == null) { mock[slot] = this._generateMock(slotMetadata, callbacks, refs); @@ -965,7 +965,7 @@ export class ModuleMocker { })(slotMetadata.ref), ); } - }); + } if ( metadata.type !== 'undefined' && @@ -1009,7 +1009,7 @@ export class ModuleMocker { const callbacks: Array = []; const refs = {}; const mock = this._generateMock(metadata, callbacks, refs); - callbacks.forEach(setter => setter()); + for (const setter of callbacks) setter(); return mock; } @@ -1060,13 +1060,13 @@ export class ModuleMocker { // Leave arrays alone if (type !== 'array') { // @ts-expect-error component is object - this._getSlots(component).forEach(slot => { + for (const slot of this._getSlots(component)) { if ( type === 'function' && this.isMockFunction(component) && slot.match(/^mock/) ) { - return; + continue; } // @ts-expect-error no index signature const slotMetadata = this.getMetadata(component[slot], refs); @@ -1076,7 +1076,7 @@ export class ModuleMocker { } members[slot] = slotMetadata; } - }); + } } if (members) { @@ -1419,7 +1419,7 @@ export class ModuleMocker { } restoreAllMocks(): void { - this._spyState.forEach(restore => restore()); + for (const restore of this._spyState) restore(); this._spyState = new Set(); } diff --git a/packages/jest-phabricator/src/index.ts b/packages/jest-phabricator/src/index.ts index 2c3ba0c84c72..95ab0ef572c7 100644 --- a/packages/jest-phabricator/src/index.ts +++ b/packages/jest-phabricator/src/index.ts @@ -16,15 +16,15 @@ function summarize(coverageMap: CoverageMap): CoverageMap { const summaries = Object.create(null); - coverageMap.files().forEach(file => { + for (const file of coverageMap.files()) { const covered = []; const lineCoverage = coverageMap.fileCoverageFor(file).getLineCoverage(); - Object.keys(lineCoverage).forEach(lineNumber => { + for (const lineNumber of Object.keys(lineCoverage)) { const number = parseInt(lineNumber, 10); // Line numbers start at one covered[number - 1] = lineCoverage[number] ? 'C' : 'U'; - }); + } for (let i = 0; i < covered.length; i++) { if (!covered[i]) { @@ -33,7 +33,7 @@ function summarize(coverageMap: CoverageMap): CoverageMap { } summaries[file] = covered.join(''); - }); + } return summaries; } diff --git a/packages/jest-reporters/src/CoverageReporter.ts b/packages/jest-reporters/src/CoverageReporter.ts index 390b793d355b..addc6ac1a5dc 100644 --- a/packages/jest-reporters/src/CoverageReporter.ts +++ b/packages/jest-reporters/src/CoverageReporter.ts @@ -78,7 +78,7 @@ export default class CoverageReporter extends BaseReporter { if (!this._globalConfig.useStderr && coverageReporters.length === 0) { coverageReporters.push('text-summary'); } - coverageReporters.forEach(reporter => { + for (let reporter of coverageReporters) { let additionalOptions = {}; if (Array.isArray(reporter)) { [reporter, additionalOptions] = reporter; @@ -89,7 +89,7 @@ export default class CoverageReporter extends BaseReporter { ...additionalOptions, }) .execute(reportContext); - }); + } aggregatedResults.coverageMap = map; } catch (e: any) { console.error( @@ -109,25 +109,22 @@ export default class CoverageReporter extends BaseReporter { ): Promise { const files: Array<{config: Config.ProjectConfig; path: string}> = []; - testContexts.forEach(context => { + for (const context of testContexts) { const config = context.config; if ( this._globalConfig.collectCoverageFrom && this._globalConfig.collectCoverageFrom.length > 0 ) { - context.hasteFS - .matchFilesWithGlob( - this._globalConfig.collectCoverageFrom, - config.rootDir, - ) - .forEach(filePath => - files.push({ - config, - path: filePath, - }), - ); + for (const filePath of context.hasteFS.matchFilesWithGlob( + this._globalConfig.collectCoverageFrom, + config.rootDir, + )) + files.push({ + config, + path: filePath, + }); } - }); + } if (files.length === 0) { return; @@ -354,7 +351,7 @@ export default class CoverageReporter extends BaseReporter { let errors: Array = []; - thresholdGroups.forEach(thresholdGroup => { + for (const thresholdGroup of thresholdGroups) { switch (groupTypeByThresholdGroup[thresholdGroup]) { case THRESHOLD_GROUP_TYPES.GLOBAL: { const coverage = combineCoverage( @@ -387,17 +384,18 @@ export default class CoverageReporter extends BaseReporter { break; } case THRESHOLD_GROUP_TYPES.GLOB: - getFilesInThresholdGroup(thresholdGroup).forEach( - fileMatchingGlob => { - errors = errors.concat( - check( - fileMatchingGlob, - coverageThreshold[thresholdGroup], - map.fileCoverageFor(fileMatchingGlob).toSummary(), - ), - ); - }, - ); + for (const fileMatchingGlob of getFilesInThresholdGroup( + thresholdGroup, + )) { + errors = errors.concat( + check( + fileMatchingGlob, + coverageThreshold[thresholdGroup], + map.fileCoverageFor(fileMatchingGlob).toSummary(), + ), + ); + } + break; default: // If the file specified by path is not found, error is returned. @@ -410,7 +408,7 @@ export default class CoverageReporter extends BaseReporter { // PATH and GLOB threshold groups in which case, don't error when // the global threshold group doesn't match any files. } - }); + } errors = errors.filter( err => err !== undefined && err !== null && err.length > 0, @@ -434,13 +432,12 @@ export default class CoverageReporter extends BaseReporter { const fileTransforms = new Map(); - this._v8CoverageResults.forEach(res => - res.forEach(r => { + for (const res of this._v8CoverageResults) + for (const r of res) { if (r.codeTransformResult && !fileTransforms.has(r.result.url)) { fileTransforms.set(r.result.url, r.codeTransformResult); } - }), - ); + } const transformedCoverage = await Promise.all( mergedCoverages.result.map(async res => { @@ -483,7 +480,7 @@ export default class CoverageReporter extends BaseReporter { const map = istanbulCoverage.createCoverageMap({}); - transformedCoverage.forEach(res => map.merge(res)); + for (const res of transformedCoverage) map.merge(res); const reportContext = istanbulReport.createContext({ coverageMap: map, diff --git a/packages/jest-reporters/src/DefaultReporter.ts b/packages/jest-reporters/src/DefaultReporter.ts index b91c8f9272d3..742b108885df 100644 --- a/packages/jest-reporters/src/DefaultReporter.ts +++ b/packages/jest-reporters/src/DefaultReporter.ts @@ -191,7 +191,7 @@ export default class DefaultReporter extends BaseReporter { result: TestResult, ): void { // log retry errors if any exist - result.testResults.forEach(testResult => { + for (const testResult of result.testResults) { const testRetryReasons = testResult.retryReasons; if (testRetryReasons && testRetryReasons.length > 0) { this.log( @@ -199,7 +199,7 @@ export default class DefaultReporter extends BaseReporter { ' LOGGING RETRY ERRORS ', )} ${chalk.bold(testResult.fullName)}`, ); - testRetryReasons.forEach((retryReasons, index) => { + for (const [index, retryReasons] of testRetryReasons.entries()) { let {message, stack} = separateMessageFromStack(retryReasons); stack = this._globalConfig.noStackTrace ? '' @@ -213,9 +213,9 @@ export default class DefaultReporter extends BaseReporter { `${chalk.reset.inverse.bold.blueBright(` RETRY ${index + 1} `)}\n`, ); this.log(`${message}\n${stack}\n`); - }); + } } - }); + } this.log(getResultHeader(result, this._globalConfig, config)); if (result.console) { @@ -239,6 +239,6 @@ export default class DefaultReporter extends BaseReporter { } const didUpdate = this._globalConfig.updateSnapshot === 'all'; const snapshotStatuses = getSnapshotStatus(result.snapshot, didUpdate); - snapshotStatuses.forEach(this.log); + for (const status of snapshotStatuses) this.log(status); } } diff --git a/packages/jest-reporters/src/GitHubActionsReporter.ts b/packages/jest-reporters/src/GitHubActionsReporter.ts index b5024068cdf2..72595756df01 100644 --- a/packages/jest-reporters/src/GitHubActionsReporter.ts +++ b/packages/jest-reporters/src/GitHubActionsReporter.ts @@ -98,27 +98,28 @@ export default class GitHubActionsReporter extends BaseReporter { {context}: Test, {testResults}: TestResult, ): void { - testResults.forEach(result => { + for (const result of testResults) { const title = [...result.ancestorTitles, result.title].join( titleSeparator, ); - result.retryReasons?.forEach((retryReason, index) => { - this.#createAnnotation({ - ...this.#getMessageDetails(retryReason, context.config), - title: `RETRY ${index + 1}: ${title}`, - type: 'warning', - }); - }); + if (result.retryReasons) + for (const [index, retryReason] of result.retryReasons.entries()) { + this.#createAnnotation({ + ...this.#getMessageDetails(retryReason, context.config), + title: `RETRY ${index + 1}: ${title}`, + type: 'warning', + }); + } - result.failureMessages.forEach(failureMessage => { + for (const failureMessage of result.failureMessages) { this.#createAnnotation({ ...this.#getMessageDetails(failureMessage, context.config), title, type: 'error', }); - }); - }); + } + } } #getMessageDetails(failureMessage: string, config: Config.ProjectConfig) { @@ -216,7 +217,7 @@ export default class GitHubActionsReporter extends BaseReporter { performanceInfo: suitePerf, }; const branches: Array> = []; - suiteResult.forEach(element => { + for (const element of suiteResult) { if (element.ancestorTitles.length === 0) { if (element.status === 'failed') { root.passed = false; @@ -242,14 +243,14 @@ export default class GitHubActionsReporter extends BaseReporter { branches.push(element.ancestorTitles.slice(0, 1)); } } - }); - branches.forEach(element => { + } + for (const element of branches) { const newChild = this.getResultChildren(suiteResult, element); if (!newChild.passed) { root.passed = false; } root.children.push(newChild); - }); + } return root; } @@ -263,7 +264,7 @@ export default class GitHubActionsReporter extends BaseReporter { passed: true, }; const branches: Array> = []; - suiteResult.forEach(element => { + for (const element of suiteResult) { let duration = element.duration; if (!duration || isNaN(duration)) { duration = 1; @@ -300,14 +301,14 @@ export default class GitHubActionsReporter extends BaseReporter { branches.push(element.ancestorTitles.slice(0, ancestors.length + 1)); } } - }); - branches.forEach(element => { + } + for (const element of branches) { const newChild = this.getResultChildren(suiteResult, element); if (!newChild.passed) { node.passed = false; } node.children.push(newChild); - }); + } return node; } @@ -324,17 +325,17 @@ export default class GitHubActionsReporter extends BaseReporter { this.startGroup( `${chalk.bold.green.inverse('PASS')} ${resultTree.name}${perfMs}`, ); - resultTree.children.forEach(child => { + for (const child of resultTree.children) { this.recursivePrintResultTree(child, true, 1); - }); + } this.endGroup(); } else { this.log( ` ${chalk.bold.red.inverse('FAIL')} ${resultTree.name}${perfMs}`, ); - resultTree.children.forEach(child => { + for (const child of resultTree.children) { this.recursivePrintResultTree(child, false, 1); - }); + } } } @@ -380,21 +381,21 @@ export default class GitHubActionsReporter extends BaseReporter { if (resultTree.passed) { if (alreadyGrouped) { this.log(' '.repeat(depth) + resultTree.name); - resultTree.children.forEach(child => { + for (const child of resultTree.children) { this.recursivePrintResultTree(child, true, depth + 1); - }); + } } else { this.startGroup(' '.repeat(depth) + resultTree.name); - resultTree.children.forEach(child => { + for (const child of resultTree.children) { this.recursivePrintResultTree(child, true, depth + 1); - }); + } this.endGroup(); } } else { this.log(' '.repeat(depth + 1) + resultTree.name); - resultTree.children.forEach(child => { + for (const child of resultTree.children) { this.recursivePrintResultTree(child, false, depth + 1); - }); + } } } } @@ -406,7 +407,7 @@ export default class GitHubActionsReporter extends BaseReporter { const rootDir = context.context.config.rootDir; const results = testResults.testResults; let written = false; - results.forEach(result => { + for (const result of results) { let testDir = result.testFilePath; testDir = testDir.replace(rootDir, ''); testDir = testDir.slice(1, testDir.length); @@ -419,7 +420,7 @@ export default class GitHubActionsReporter extends BaseReporter { this.log(result.failureMessage); this.endGroup(); } - }); + } return written; } diff --git a/packages/jest-reporters/src/Status.ts b/packages/jest-reporters/src/Status.ts index 46099055fe8c..2a53af30331f 100644 --- a/packages/jest-reporters/src/Status.ts +++ b/packages/jest-reporters/src/Status.ts @@ -162,7 +162,7 @@ export default class Status { const width = process.stdout.columns; let content = '\n'; - this._currentTests.get().forEach(record => { + for (const record of this._currentTests.get()) { if (record) { const {config, testPath} = record; @@ -177,7 +177,7 @@ export default class Status { width, )}\n`; } - }); + } if (this._showStatus && this._aggregatedResults) { content += `\n${getSummary(this._aggregatedResults, { diff --git a/packages/jest-reporters/src/SummaryReporter.ts b/packages/jest-reporters/src/SummaryReporter.ts index ed7842fedebb..3c43b62367d9 100644 --- a/packages/jest-reporters/src/SummaryReporter.ts +++ b/packages/jest-reporters/src/SummaryReporter.ts @@ -177,7 +177,7 @@ export default class SummaryReporter extends BaseReporter { globalConfig, updateCommand, ); - snapshotSummary.forEach(this.log); + for (const summary of snapshotSummary) this.log(summary); this.log(''); // print empty line } @@ -196,14 +196,14 @@ export default class SummaryReporter extends BaseReporter { aggregatedResults.numTotalTestSuites > this._summaryThreshold ) { this.log(chalk.bold('Summary of all failing tests')); - aggregatedResults.testResults.forEach(testResult => { + for (const testResult of aggregatedResults.testResults) { const {failureMessage} = testResult; if (failureMessage) { this._write( `${getResultHeader(testResult, globalConfig)}\n${failureMessage}\n`, ); } - }); + } this.log(''); // print empty line } } diff --git a/packages/jest-reporters/src/VerboseReporter.ts b/packages/jest-reporters/src/VerboseReporter.ts index 46ae16d6a4b1..fb2263269e8d 100644 --- a/packages/jest-reporters/src/VerboseReporter.ts +++ b/packages/jest-reporters/src/VerboseReporter.ts @@ -52,7 +52,7 @@ export default class VerboseReporter extends DefaultReporter { static groupTestsBySuites(testResults: Array): Suite { const root: Suite = {suites: [], tests: [], title: ''}; - testResults.forEach(testResult => { + for (const testResult of testResults) { let targetSuite = root; // Find the target suite for this test, @@ -67,7 +67,7 @@ export default class VerboseReporter extends DefaultReporter { } targetSuite.tests.push(testResult); - }); + } return root; } @@ -107,7 +107,9 @@ export default class VerboseReporter extends DefaultReporter { this._logTests(suite.tests, indentLevel + 1); - suite.suites.forEach(suite => this._logSuite(suite, indentLevel + 1)); + for (const innerSuite of suite.suites) { + this._logSuite(innerSuite, indentLevel + 1); + } } private _getIcon(status: string) { @@ -132,7 +134,7 @@ export default class VerboseReporter extends DefaultReporter { private _logTests(tests: Array, indentLevel: number) { if (this._globalConfig.expand) { - tests.forEach(test => this._logTest(test, indentLevel)); + for (const test of tests) this._logTest(test, indentLevel); } else { const summedTests = tests.reduce<{ pending: Array; @@ -152,12 +154,13 @@ export default class VerboseReporter extends DefaultReporter { {pending: [], todo: []}, ); + const logTodoOrPendingTest = this._logTodoOrPendingTest(indentLevel); if (summedTests.pending.length > 0) { - summedTests.pending.forEach(this._logTodoOrPendingTest(indentLevel)); + for (const test of summedTests.pending) logTodoOrPendingTest(test); } if (summedTests.todo.length > 0) { - summedTests.todo.forEach(this._logTodoOrPendingTest(indentLevel)); + for (const test of summedTests.todo) logTodoOrPendingTest(test); } } } diff --git a/packages/jest-reporters/src/__tests__/CoverageReporter.test.js b/packages/jest-reporters/src/__tests__/CoverageReporter.test.js index 847fd27133e8..41763405773f 100644 --- a/packages/jest-reporters/src/__tests__/CoverageReporter.test.js +++ b/packages/jest-reporters/src/__tests__/CoverageReporter.test.js @@ -159,16 +159,15 @@ describe('onRunComplete', () => { test('getLastError() returns an error when threshold is not met for file', () => { const covThreshold = {}; - [ + const paths = [ 'global', path.resolve(`${process.cwd()}/path-test-files/full_path_file.js`), './path-test-files/relative_path_file.js', 'path-test-files/glob-*/*.js', - ].forEach(path => { - covThreshold[path] = { - statements: 100, - }; - }); + ]; + for (const path of paths) { + covThreshold[path] = {statements: 100}; + } const testReporter = new CoverageReporter( { @@ -189,16 +188,15 @@ describe('onRunComplete', () => { test('getLastError() returns `undefined` when threshold is met', () => { const covThreshold = {}; - [ + const paths = [ 'global', path.resolve(`${process.cwd()}/path-test-files/full_path_file.js`), './path-test-files/relative_path_file.js', 'path-test-files/glob-*/*.js', - ].forEach(path => { - covThreshold[path] = { - statements: 50, - }; - }); + ]; + for (const path of paths) { + covThreshold[path] = {statements: 50}; + } const testReporter = new CoverageReporter( { @@ -338,7 +336,7 @@ describe('onRunComplete', () => { test(`getLastError() returns 'undefined' when file and directory path threshold groups overlap`, () => { const covThreshold = {}; - [ + for (const path of [ './path-test-files/', './path-test-files/covered_file_without_threshold.js', './path-test-files/full_path_file.js', @@ -346,11 +344,11 @@ describe('onRunComplete', () => { './path-test-files/glob-path/file1.js', './path-test-files/glob-path/file2.js', './path-test-files/*.js', - ].forEach(path => { + ]) { covThreshold[path] = { statements: 0, }; - }); + } const testReporter = new CoverageReporter( { diff --git a/packages/jest-reporters/src/__tests__/NotifyReporter.test.ts b/packages/jest-reporters/src/__tests__/NotifyReporter.test.ts index 15d4ce1f2375..6f72a851c0c5 100644 --- a/packages/jest-reporters/src/__tests__/NotifyReporter.test.ts +++ b/packages/jest-reporters/src/__tests__/NotifyReporter.test.ts @@ -83,7 +83,7 @@ const testModes = ({ const globalConfig = makeGlobalConfig({notify: true, notifyMode, rootDir}); let previousContext = initialContext; - arl.forEach((ar, i) => { + for (const [i, ar] of arl.entries()) { const newContext: ReporterContext = Object.assign(previousContext, { firstRun: i === 0, previousSuccess: previousContext.previousSuccess, @@ -111,7 +111,7 @@ const testModes = ({ if (ar.numTotalTests === 0) { expect(notify.notify).not.toHaveBeenCalled(); } - }); + } const calls: Array = notify.notify.mock.calls; expect( diff --git a/packages/jest-reporters/src/getSnapshotStatus.ts b/packages/jest-reporters/src/getSnapshotStatus.ts index 213b7f4114c1..9a58f3d33387 100644 --- a/packages/jest-reporters/src/getSnapshotStatus.ts +++ b/packages/jest-reporters/src/getSnapshotStatus.ts @@ -61,9 +61,9 @@ export default function getSnapshotStatus( ); } - snapshot.uncheckedKeys.forEach(key => { + for (const key of snapshot.uncheckedKeys) { statuses.push(` ${DOT}${key}`); - }); + } } if (snapshot.fileDeleted) { diff --git a/packages/jest-reporters/src/getSnapshotSummary.ts b/packages/jest-reporters/src/getSnapshotSummary.ts index 988dd97429bb..535b3f3f36d6 100644 --- a/packages/jest-reporters/src/getSnapshotSummary.ts +++ b/packages/jest-reporters/src/getSnapshotSummary.ts @@ -90,9 +90,9 @@ export default function getSnapshotSummary( const [head, ...tail] = snapshots.filesRemovedList; summary.push(` ${DOWN_ARROW} ${DOT}${formatTestPath(globalConfig, head)}`); - tail.forEach(key => { + for (const key of tail) { summary.push(` ${DOT}${formatTestPath(globalConfig, key)}`); - }); + } } if (snapshots.unchecked) { @@ -120,7 +120,7 @@ export default function getSnapshotSummary( ); } - snapshots.uncheckedKeysByFile.forEach(uncheckedFile => { + for (const uncheckedFile of snapshots.uncheckedKeysByFile) { summary.push( ` ${DOWN_ARROW}${formatTestPath( globalConfig, @@ -128,10 +128,10 @@ export default function getSnapshotSummary( )}`, ); - uncheckedFile.keys.forEach(key => { + for (const key of uncheckedFile.keys) { summary.push(` ${DOT}${key}`); - }); - }); + } + } } return summary; diff --git a/packages/jest-reporters/src/getSummary.ts b/packages/jest-reporters/src/getSummary.ts index d01b15d1b2f7..6e2bb5fe3725 100644 --- a/packages/jest-reporters/src/getSummary.ts +++ b/packages/jest-reporters/src/getSummary.ts @@ -20,7 +20,7 @@ function getValuesCurrentTestCases( let numPendingTests = 0; let numTodoTests = 0; let numTotalTests = 0; - currentTestCases.forEach(testCase => { + for (const testCase of currentTestCases) { switch (testCase.testCaseResult.status) { case 'failed': { numFailingTests++; @@ -40,7 +40,7 @@ function getValuesCurrentTestCases( } } numTotalTests++; - }); + } return { numFailingTests, diff --git a/packages/jest-resolve/src/__tests__/resolve.test.ts b/packages/jest-resolve/src/__tests__/resolve.test.ts index a027d1065aab..e71224bf5a38 100644 --- a/packages/jest-resolve/src/__tests__/resolve.test.ts +++ b/packages/jest-resolve/src/__tests__/resolve.test.ts @@ -834,9 +834,8 @@ describe('Resolver.getGlobalPaths()', () => { jest.doMock('path', () => _path.posix); const resolver = new Resolver(moduleMap, {} as ResolverConfig); const globalPaths = resolver.getGlobalPaths('jest'); - globalPaths.forEach(globalPath => - expect(require.resolve.paths('jest')).toContain(globalPath), - ); + for (const globalPath of globalPaths) + expect(require.resolve.paths('jest')).toContain(globalPath); }); it('return empty array with builtin module', () => { @@ -850,9 +849,8 @@ describe('Resolver.getGlobalPaths()', () => { jest.doMock('path', () => _path.posix); const resolver = new Resolver(moduleMap, {} as ResolverConfig); const globalPaths = resolver.getGlobalPaths('/'); - globalPaths.forEach(globalPath => - expect(require.resolve.paths('/')).toContain(globalPath), - ); + for (const globalPath of globalPaths) + expect(require.resolve.paths('/')).toContain(globalPath); }); it('return empty array with relative path', () => { diff --git a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js index 46bd064769e8..1d38f0eefafb 100644 --- a/packages/jest-runtime/src/__tests__/runtime_require_module.test.js +++ b/packages/jest-runtime/src/__tests__/runtime_require_module.test.js @@ -137,23 +137,23 @@ describe('Runtime requireModule', () => { const root = path.parse(process.cwd()).root; const globalPath = path.join(root, 'node_modules'); const rootIndex = exports.paths.findIndex(path => path === globalPath); - exports.paths.forEach((path, index) => { + for (const [index, path] of exports.paths.entries()) { if (index <= rootIndex) { expect(moduleDirectories.some(dir => path.endsWith(dir))).toBe(true); } - }); + } }); it('provides `require.main` to modules', async () => { const runtime = await createRuntime(__filename); runtime._mainModule = module; - [ + for (const modulePath of [ './test_root/modules_with_main/export_main.js', './test_root/modules_with_main/re_export_main.js', - ].forEach(modulePath => { + ]) { const mainModule = runtime.requireModule(__filename, modulePath); expect(mainModule).toBe(module); - }); + } }); it('throws on non-existent haste modules', async () => { diff --git a/packages/jest-runtime/src/__tests__/test_root/test_json_preprocessor.js b/packages/jest-runtime/src/__tests__/test_root/test_json_preprocessor.js index 468d225ea22c..526d084ca578 100644 --- a/packages/jest-runtime/src/__tests__/test_root/test_json_preprocessor.js +++ b/packages/jest-runtime/src/__tests__/test_root/test_json_preprocessor.js @@ -9,6 +9,6 @@ module.exports.process = source => { const json = JSON.parse(source); - Object.keys(json).forEach(k => (json[k] = k)); + for (const k of Object.keys(json)) json[k] = k; return {code: JSON.stringify(json)}; }; diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index 61074414b2b5..839986c0a871 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -289,7 +289,7 @@ export default class Runtime { ); if (config.automock) { - config.setupFiles.forEach(filePath => { + for (const filePath of config.setupFiles) { if (filePath.includes(NODE_MODULES)) { const moduleID = this._resolver.getModuleID( this._virtualMocks, @@ -304,7 +304,7 @@ export default class Runtime { ); this._transitiveShouldMock.set(moduleID, false); } - }); + } } this.resetModules(); @@ -778,10 +778,10 @@ export default class Runtime { const module = new SyntheticModule( [...cjsExports, 'default'], function () { - cjsExports.forEach(exportName => { + for (const exportName of cjsExports) { // @ts-expect-error: TS doesn't know what `this` is this.setExport(exportName, cjs[exportName]); - }); + } // @ts-expect-error: TS doesn't know what `this` is this.setExport('default', cjs); }, @@ -816,10 +816,10 @@ export default class Runtime { const module = new SyntheticModule( Object.keys(invokedFactory), function () { - Object.entries(invokedFactory).forEach(([key, value]) => { + for (const [key, value] of Object.entries(invokedFactory)) { // @ts-expect-error: TS doesn't know what `this` is this.setExport(key, value); - }); + } }, {context, identifier: moduleName}, ); @@ -846,20 +846,20 @@ export default class Runtime { const namedExports = new Set(exports); - reexports.forEach(reexport => { + for (const reexport of reexports) { if (this._resolver.isCoreModule(reexport)) { const exports = this.requireModule(modulePath, reexport); if (exports !== null && typeof exports === 'object') { - Object.keys(exports).forEach(namedExports.add, namedExports); + for (const e of Object.keys(exports)) namedExports.add(e); } } else { const resolved = this._resolveCjsModule(modulePath, reexport); const exports = this.getExportsOfCjs(resolved); - exports.forEach(namedExports.add, namedExports); + for (const e of exports) namedExports.add(e); } - }); + } this._cjsNamedExports.set(modulePath, namedExports); @@ -1224,19 +1224,19 @@ export default class Runtime { if (this._environment) { if (this._environment.global) { const envGlobal = this._environment.global; - (Object.keys(envGlobal) as Array).forEach( - key => { - const globalMock = envGlobal[key]; - if ( - ((typeof globalMock === 'object' && globalMock !== null) || - typeof globalMock === 'function') && - '_isMockFunction' in globalMock && - globalMock._isMockFunction === true - ) { - globalMock.mockClear(); - } - }, - ); + for (const key of Object.keys(envGlobal) as Array< + keyof typeof globalThis + >) { + const globalMock = envGlobal[key]; + if ( + ((typeof globalMock === 'object' && globalMock !== null) || + typeof globalMock === 'function') && + '_isMockFunction' in globalMock && + globalMock._isMockFunction === true + ) { + globalMock.mockClear(); + } + } } if (this._environment.fakeTimers) { @@ -1717,10 +1717,10 @@ export default class Runtime { function () { // @ts-expect-error: TS doesn't know what `this` is this.setExport('default', required); - Object.entries(required).forEach(([key, value]) => { + for (const [key, value] of Object.entries(required)) { // @ts-expect-error: TS doesn't know what `this` is this.setExport(key, value); - }); + } }, // should identifier be `node://${moduleName}`? {context, identifier: moduleName}, @@ -1812,10 +1812,10 @@ export default class Runtime { // should we implement the class ourselves? class Module extends nativeModule.Module {} - Object.entries(nativeModule.Module).forEach(([key, value]) => { + for (const [key, value] of Object.entries(nativeModule.Module)) { // @ts-expect-error: no index signature Module[key] = value; - }); + } Module.Module = Module; @@ -2471,10 +2471,10 @@ export default class Runtime { const module = new SyntheticModule( Object.keys(globals), function () { - Object.entries(globals).forEach(([key, value]) => { + for (const [key, value] of Object.entries(globals)) { // @ts-expect-error: TS doesn't know what `this` is this.setExport(key, value); - }); + } }, {context, identifier: '@jest/globals'}, ); diff --git a/packages/jest-snapshot/src/SnapshotResolver.ts b/packages/jest-snapshot/src/SnapshotResolver.ts index 7abfe5e6534f..bd34e2037a0a 100644 --- a/packages/jest-snapshot/src/SnapshotResolver.ts +++ b/packages/jest-snapshot/src/SnapshotResolver.ts @@ -92,11 +92,11 @@ async function createCustomSnapshotResolver( ['resolveTestPath', 'function'], ['testPathForConsistencyCheck', 'string'], ]; - keys.forEach(([propName, requiredType]) => { + for (const [propName, requiredType] of keys) { if (typeof custom[propName] !== requiredType) { throw new TypeError(mustImplement(propName, requiredType)); } - }); + } const customResolver: SnapshotResolver = { resolveSnapshotPath: (testPath: string) => diff --git a/packages/jest-snapshot/src/State.ts b/packages/jest-snapshot/src/State.ts index efa6fba2d1c0..1f9a46e6d386 100644 --- a/packages/jest-snapshot/src/State.ts +++ b/packages/jest-snapshot/src/State.ts @@ -98,11 +98,11 @@ export default class SnapshotState { } markSnapshotsAsCheckedForTest(testName: string): void { - this._uncheckedKeys.forEach(uncheckedKey => { + for (const uncheckedKey of this._uncheckedKeys) { if (keyToTestName(uncheckedKey) === testName) { this._uncheckedKeys.delete(uncheckedKey); } - }); + } } private _addSnapshot( @@ -186,7 +186,7 @@ export default class SnapshotState { removeUncheckedKeys(): void { if (this._updateSnapshot === 'all' && this._uncheckedKeys.size > 0) { this._dirty = true; - this._uncheckedKeys.forEach(key => delete this._snapshotData[key]); + for (const key of this._uncheckedKeys) delete this._snapshotData[key]; this._uncheckedKeys.clear(); } } diff --git a/packages/jest-snapshot/src/__tests__/plugins.test.ts b/packages/jest-snapshot/src/__tests__/plugins.test.ts index f776f5ffd3b2..2ffd3f834474 100644 --- a/packages/jest-snapshot/src/__tests__/plugins.test.ts +++ b/packages/jest-snapshot/src/__tests__/plugins.test.ts @@ -21,10 +21,7 @@ const testPath = (names: Array) => { // Jest tests snapshotSerializers in order preceding built-in serializers. // Therefore, add in reverse because the last added is the first tested. - added - .concat() - .reverse() - .forEach(serializer => addSerializer(serializer)); + for (const serializer of added.concat().reverse()) addSerializer(serializer); const next = getSerializers(); expect(next).toHaveLength(added.length + prev.length); diff --git a/packages/jest-snapshot/src/utils.ts b/packages/jest-snapshot/src/utils.ts index e7e9edfd9b17..74c499c2a2a2 100644 --- a/packages/jest-snapshot/src/utils.ts +++ b/packages/jest-snapshot/src/utils.ts @@ -228,7 +228,7 @@ const isAnyOrAnything = (input: object) => const deepMergeArray = (target: Array, source: Array) => { const mergedOutput = Array.from(target); - source.forEach((sourceElement, index) => { + for (const [index, sourceElement] of source.entries()) { const targetElement = mergedOutput[index]; if (Array.isArray(target[index]) && Array.isArray(sourceElement)) { @@ -239,7 +239,7 @@ const deepMergeArray = (target: Array, source: Array) => { // Source does not exist in target or target is primitive and cannot be deep merged mergedOutput[index] = sourceElement; } - }); + } return mergedOutput; }; @@ -249,7 +249,7 @@ export const deepMerge = (target: any, source: any): any => { if (isObject(target) && isObject(source)) { const mergedOutput = {...target}; - Object.keys(source).forEach(key => { + for (const key of Object.keys(source)) { if (isObject(source[key]) && !source[key].$$typeof) { if (key in target) { mergedOutput[key] = deepMerge(target[key], source[key]); @@ -261,7 +261,7 @@ export const deepMerge = (target: any, source: any): any => { } else { Object.assign(mergedOutput, {[key]: source[key]}); } - }); + } return mergedOutput; } else if (Array.isArray(target) && Array.isArray(source)) { diff --git a/packages/jest-test-sequencer/src/index.ts b/packages/jest-test-sequencer/src/index.ts index 9495c3d49470..4a3b01883a5c 100644 --- a/packages/jest-test-sequencer/src/index.ts +++ b/packages/jest-test-sequencer/src/index.ts @@ -194,9 +194,9 @@ export default class TestSequencer { const fileSize = ({path, context: {hasteFS}}: Test) => stats[path] || (stats[path] = hasteFS.getSize(path) ?? 0); - tests.forEach(test => { + for (const test of tests) { test.duration = this.time(test); - }); + } return tests.sort((testA, testB) => { const failedA = this.hasFailed(testA); const failedB = this.hasFailed(testB); @@ -220,8 +220,8 @@ export default class TestSequencer { cacheResults(tests: Array, results: AggregatedResult): void { const map = Object.create(null) as Record; - tests.forEach(test => (map[test.path] = test)); - results.testResults.forEach(testResult => { + for (const test of tests) map[test.path] = test; + for (const testResult of results.testResults) { const test = map[testResult.testFilePath]; if (test != null && !testResult.skipped) { const cache = this._getCache(test); @@ -233,11 +233,10 @@ export default class TestSequencer { testRuntime || 0, ]; } - }); + } - this._cache.forEach((cache, context) => - fs.writeFileSync(this._getCachePath(context), JSON.stringify(cache)), - ); + for (const [context, cache] of this._cache.entries()) + fs.writeFileSync(this._getCachePath(context), JSON.stringify(cache)); } private hasFailed(test: Test) { diff --git a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts index 47fcb9f5aa8f..975993e59b98 100644 --- a/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts +++ b/packages/jest-transform/src/__tests__/ScriptTransformer.test.ts @@ -438,7 +438,7 @@ describe('ScriptTransformer', () => { [[], '/fruits/grapefruit.js'], ]; - incorrectReturnValues.forEach(([returnValue, filePath]) => { + for (const [returnValue, filePath] of incorrectReturnValues) { mockInvariant(typeof filePath === 'string'); jest .mocked( @@ -448,11 +448,11 @@ describe('ScriptTransformer', () => { expect(() => scriptTransformer.transform(filePath, getCoverageOptions()), ).toThrowErrorMatchingSnapshot(); - }); + } const correctReturnValues = [[{code: 'code'}, '/fruits/kiwi.js']]; - correctReturnValues.forEach(([returnValue, filePath]) => { + for (const [returnValue, filePath] of correctReturnValues) { mockInvariant(typeof filePath === 'string'); jest .mocked( @@ -462,7 +462,7 @@ describe('ScriptTransformer', () => { expect(() => scriptTransformer.transform(filePath, getCoverageOptions()), ).not.toThrow(); - }); + } }); it("throws an error if `processAsync` doesn't return a promise of object containing `code` key with processed string", async () => { diff --git a/packages/jest-util/src/__tests__/createProcessObject.test.ts b/packages/jest-util/src/__tests__/createProcessObject.test.ts index b3648daa0ec2..aa2711b13761 100644 --- a/packages/jest-util/src/__tests__/createProcessObject.test.ts +++ b/packages/jest-util/src/__tests__/createProcessObject.test.ts @@ -27,12 +27,12 @@ it('creates a process object that looks like the original one', () => { // They look the same, but they are NOT the same (deep copied object). // The `_events` property is checked to ensure event emitter properties are // properly copied. - (['argv', 'env', '_events'] as const).forEach(key => { + for (const key of ['argv', 'env', '_events'] as const) { // @ts-expect-error: Testing internal `_events` property expect(fakeProcess[key]).toEqual(process[key]); // @ts-expect-error: Testing internal `_events` property expect(fakeProcess[key]).not.toBe(process[key]); - }); + } // Check that process.stdout/stderr are the same. expect(process.stdout).toBe(fakeProcess.stdout); diff --git a/packages/jest-util/src/deepCyclicCopy.ts b/packages/jest-util/src/deepCyclicCopy.ts index 7c681640efcc..10d123858b04 100644 --- a/packages/jest-util/src/deepCyclicCopy.ts +++ b/packages/jest-util/src/deepCyclicCopy.ts @@ -41,10 +41,10 @@ function deepCyclicCopyObject( cycles.set(object, newObject); - Object.keys(descriptors).forEach(key => { + for (const key of Object.keys(descriptors)) { if (options.blacklist && options.blacklist.has(key)) { delete descriptors[key]; - return; + continue; } const descriptor = descriptors[key]; @@ -57,7 +57,7 @@ function deepCyclicCopyObject( } descriptor.configurable = true; - }); + } return Object.defineProperties(newObject, descriptors); } diff --git a/packages/jest-util/src/installCommonGlobals.ts b/packages/jest-util/src/installCommonGlobals.ts index 4920d949dc27..b9ec8483f3ab 100644 --- a/packages/jest-util/src/installCommonGlobals.ts +++ b/packages/jest-util/src/installCommonGlobals.ts @@ -54,13 +54,13 @@ export default function installCommonGlobals( }); // Forward some APIs. - DTRACE.forEach(dtrace => { + for (const dtrace of DTRACE) { // @ts-expect-error: no index globalObject[dtrace] = function (...args: Array) { // @ts-expect-error: no index return globalThis[dtrace].apply(this, args); }; - }); + } return Object.assign(globalObject, deepCyclicCopy(globals)); } diff --git a/packages/jest-validate/src/validateCLIOptions.ts b/packages/jest-validate/src/validateCLIOptions.ts index 5cb8ddce950a..50c47b8dfe3f 100644 --- a/packages/jest-validate/src/validateCLIOptions.ts +++ b/packages/jest-validate/src/validateCLIOptions.ts @@ -60,7 +60,7 @@ const validateDeprecatedOptions = ( deprecationEntries: DeprecatedOptions, argv: Config.Argv, ) => { - deprecatedOptions.forEach(opt => { + for (const opt of deprecatedOptions) { const name = opt.name; const message = deprecationEntries[name](argv); const comment = DOCUMENTATION_NOTE; @@ -70,7 +70,7 @@ const validateDeprecatedOptions = ( } else { logValidationWarning(name, message, comment); } - }); + } }; export default function validateCLIOptions( diff --git a/packages/jest-watcher/src/JestHooks.ts b/packages/jest-watcher/src/JestHooks.ts index 536f7962fad2..9797887bb9ac 100644 --- a/packages/jest-watcher/src/JestHooks.ts +++ b/packages/jest-watcher/src/JestHooks.ts @@ -48,12 +48,13 @@ class JestHooks { }; this._emitter = { - onFileChange: fs => - this._listeners.onFileChange.forEach(listener => listener(fs)), - onTestRunComplete: results => - this._listeners.onTestRunComplete.forEach(listener => - listener(results), - ), + onFileChange: fs => { + for (const listener of this._listeners.onFileChange) listener(fs); + }, + onTestRunComplete: results => { + for (const listener of this._listeners.onTestRunComplete) + listener(results); + }, shouldRunTestSuite: async testSuiteInfo => { const result = await Promise.all( this._listeners.shouldRunTestSuite.map(listener => diff --git a/packages/jest-watcher/src/lib/__tests__/formatTestNameByPattern.test.ts b/packages/jest-watcher/src/lib/__tests__/formatTestNameByPattern.test.ts index 1854e68f8a7e..ce5b063400f4 100644 --- a/packages/jest-watcher/src/lib/__tests__/formatTestNameByPattern.test.ts +++ b/packages/jest-watcher/src/lib/__tests__/formatTestNameByPattern.test.ts @@ -17,9 +17,9 @@ describe('for multiline test name returns', () => { it('test name with highlighted pattern and replaced line breaks', () => { const pattern = 'name'; - testNames.forEach(testName => { + for (const testName of testNames) { expect(formatTestNameByPattern(testName, pattern, 36)).toMatchSnapshot(); - }); + } }); }); diff --git a/packages/jest-worker/src/Farm.ts b/packages/jest-worker/src/Farm.ts index ff7e06f48f54..990ef4b68ed7 100644 --- a/packages/jest-worker/src/Farm.ts +++ b/packages/jest-worker/src/Farm.ts @@ -55,7 +55,7 @@ export default class Farm { }; const onCustomMessage: OnCustomMessage = message => { - customMessageListeners.forEach(listener => listener(message)); + for (const listener of customMessageListeners) listener(message); }; const promise: PromiseWithCustomMessage = new Promise( diff --git a/packages/jest-worker/src/__tests__/process-integration.test.ts b/packages/jest-worker/src/__tests__/process-integration.test.ts index 9d1ffff3da8c..e688fe80c005 100644 --- a/packages/jest-worker/src/__tests__/process-integration.test.ts +++ b/packages/jest-worker/src/__tests__/process-integration.test.ts @@ -33,13 +33,13 @@ function assertCallsToChild( calls.length + 1, ); - calls.forEach(([methodName, ...args], numCall) => { + for (const [numCall, [methodName, ...args]] of calls.entries()) { expect( jest.mocked(mockForkedProcesses[childNum].send).mock.calls[ numCall + 1 ][0], ).toEqual([CHILD_MESSAGE_CALL, true, methodName, args]); - }); + } } describe('Jest Worker Integration', () => { diff --git a/packages/jest-worker/src/__tests__/thread-integration.test.ts b/packages/jest-worker/src/__tests__/thread-integration.test.ts index bfffc2d3c96c..9f76c09c9088 100644 --- a/packages/jest-worker/src/__tests__/thread-integration.test.ts +++ b/packages/jest-worker/src/__tests__/thread-integration.test.ts @@ -25,13 +25,13 @@ function assertCallsToChild( calls.length + 1, ); - calls.forEach(([methodName, ...args], numCall) => { + for (const [numCall, [methodName, ...args]] of calls.entries()) { expect( jest.mocked(mockForkedProcesses[childNum].postMessage).mock.calls[ numCall + 1 ][0], ).toEqual([CHILD_MESSAGE_CALL, true, methodName, args]); - }); + } } describe('Jest Worker Process Integration', () => { diff --git a/packages/jest-worker/src/index.ts b/packages/jest-worker/src/index.ts index 16afcc351525..a92ffba8bb42 100644 --- a/packages/jest-worker/src/index.ts +++ b/packages/jest-worker/src/index.ts @@ -147,9 +147,9 @@ export class Worker { workerPath: string, options: WorkerFarmOptions, ): void { - getExposedMethods(workerPath, options).forEach(name => { + for (const name of getExposedMethods(workerPath, options)) { if (name.startsWith('_')) { - return; + continue; } // eslint-disable-next-line no-prototype-builtins @@ -159,7 +159,7 @@ export class Worker { // @ts-expect-error: dynamic extension of the class instance is expected. this[name] = this._callFunctionWithArgs.bind(this, name); - }); + } } private _callFunctionWithArgs( diff --git a/packages/pretty-format/__benchmarks__/test.js b/packages/pretty-format/__benchmarks__/test.js index c648cbace774..3e808e189d56 100644 --- a/packages/pretty-format/__benchmarks__/test.js +++ b/packages/pretty-format/__benchmarks__/test.js @@ -77,10 +77,10 @@ function test(name, value, ignoreResult, prettyFormatOpts) { const winner = results[0]; - results.forEach((item, index) => { + for (const [index, item] of results.entries()) { item.isWinner = index === 0; item.isLoser = index === results.length - 1; - }); + } function log(current) { let message = current.name; @@ -124,7 +124,7 @@ function test(name, value, ignoreResult, prettyFormatOpts) { } console.log(`${name}: `); - results.forEach(log); + for (const r of results) log(r); console.log(); } diff --git a/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts b/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts index 17de1bc9506f..bdeaab84acc4 100644 --- a/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts +++ b/packages/pretty-format/src/__tests__/AsymmetricMatcher.test.ts @@ -24,7 +24,7 @@ beforeEach(() => { options = {plugins: [AsymmetricMatcher]}; }); -[ +for (const type of [ String, Function, Array, @@ -34,7 +34,7 @@ beforeEach(() => { Function, () => {}, function namedFunction() {}, -].forEach(type => { +]) { test(`supports any(${fnNameFor(type)})`, () => { const result = prettyFormat(expect.any(type), options); expect(result).toBe(`Any<${fnNameFor(type)}>`); @@ -55,7 +55,7 @@ beforeEach(() => { )}>,\n },\n}`, ); }); -}); +} test('anything()', () => { const result = prettyFormat(expect.anything(), options); diff --git a/packages/pretty-format/src/__tests__/DOMElement.test.ts b/packages/pretty-format/src/__tests__/DOMElement.test.ts index 1611cac1bd17..7f05d4761a1f 100644 --- a/packages/pretty-format/src/__tests__/DOMElement.test.ts +++ b/packages/pretty-format/src/__tests__/DOMElement.test.ts @@ -318,11 +318,11 @@ Testing.`; 'Internet Explorer', ]; - browsers.forEach(browser => { + for (const browser of browsers) { const li = document.createElement('li'); li.textContent = browser; fragment.appendChild(li); - }); + } expect(fragment).toPrettyPrintTo( [ diff --git a/packages/pretty-format/src/collections.ts b/packages/pretty-format/src/collections.ts index d5911ba05ff5..d87fd41132e8 100644 --- a/packages/pretty-format/src/collections.ts +++ b/packages/pretty-format/src/collections.ts @@ -17,11 +17,11 @@ const getKeysOfEnumerableProperties = ( compareKeys === null ? rawKeys : rawKeys.sort(compareKeys); if (Object.getOwnPropertySymbols) { - Object.getOwnPropertySymbols(object).forEach(symbol => { + for (const symbol of Object.getOwnPropertySymbols(object)) { if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) { keys.push(symbol); } - }); + } } return keys as Array; diff --git a/packages/pretty-format/src/index.ts b/packages/pretty-format/src/index.ts index d0522eec5f62..ccbce04190a5 100644 --- a/packages/pretty-format/src/index.ts +++ b/packages/pretty-format/src/index.ts @@ -420,11 +420,11 @@ export const DEFAULT_OPTIONS = toOptionsSubtype({ }); function validateOptions(options: OptionsReceived) { - Object.keys(options).forEach(key => { + for (const key of Object.keys(options)) { if (!Object.prototype.hasOwnProperty.call(DEFAULT_OPTIONS, key)) { throw new Error(`pretty-format: Unknown option "${key}".`); } - }); + } if (options.min && options.indent !== undefined && options.indent !== 0) { throw new Error( diff --git a/packages/pretty-format/src/plugins/ReactElement.ts b/packages/pretty-format/src/plugins/ReactElement.ts index d073c77651b1..7026b690eda2 100644 --- a/packages/pretty-format/src/plugins/ReactElement.ts +++ b/packages/pretty-format/src/plugins/ReactElement.ts @@ -18,9 +18,9 @@ import { // return flattened array of children. const getChildren = (arg: unknown, children: Array = []) => { if (Array.isArray(arg)) { - arg.forEach(item => { + for (const item of arg) { getChildren(item, children); - }); + } } else if (arg != null && arg !== false) { children.push(arg); } diff --git a/packages/test-utils/src/config.ts b/packages/test-utils/src/config.ts index b427dcc9e3fb..a27bf9c874b1 100644 --- a/packages/test-utils/src/config.ts +++ b/packages/test-utils/src/config.ts @@ -132,7 +132,8 @@ export const makeGlobalConfig = ( overrides: Partial = {}, ): Config.GlobalConfig => { const overridesKeys = new Set(Object.keys(overrides)); - Object.keys(DEFAULT_GLOBAL_CONFIG).forEach(key => overridesKeys.delete(key)); + for (const key of Object.keys(DEFAULT_GLOBAL_CONFIG)) + overridesKeys.delete(key); if (overridesKeys.size > 0) { throw new Error(` @@ -148,7 +149,8 @@ export const makeProjectConfig = ( overrides: Partial = {}, ): Config.ProjectConfig => { const overridesKeys = new Set(Object.keys(overrides)); - Object.keys(DEFAULT_PROJECT_CONFIG).forEach(key => overridesKeys.delete(key)); + for (const key of Object.keys(DEFAULT_PROJECT_CONFIG)) + overridesKeys.delete(key); if (overridesKeys.size > 0) { throw new Error(` diff --git a/scripts/build.mjs b/scripts/build.mjs index 804185c1d257..29f1f79c92e3 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -66,7 +66,7 @@ function buildNodePackage({packageDir, pkg}) { process.stdout.write(adjustToTerminalWidth(`${pkg.name}\n`)); - files.forEach(file => buildFile(file, true)); + for (const file of files) buildFile(file, true); assert.ok( fs.existsSync(path.resolve(packageDir, pkg.main)), @@ -150,9 +150,9 @@ function buildFile(file, silent) { const files = process.argv.slice(2); if (files.length > 0) { - files.forEach(file => buildFile(file)); + for (const file of files) buildFile(file); } else { const packages = getPackages(); process.stdout.write(chalk.inverse(' Building packages \n')); - packages.forEach(buildNodePackage); + for (const pkg of packages) buildNodePackage(pkg); } diff --git a/scripts/buildTs.mjs b/scripts/buildTs.mjs index 4580c85390dd..2a49d08cbae4 100644 --- a/scripts/buildTs.mjs +++ b/scripts/buildTs.mjs @@ -32,7 +32,7 @@ const workspacesWithTs = new Map( .map(({location, name}) => [name, location]), ); -packagesWithTs.forEach(({packageDir, pkg}) => { +for (const {packageDir, pkg} of packagesWithTs) { assert.ok(pkg.types, `Package ${pkg.name} is missing \`types\` field`); assert.strictEqual( @@ -148,7 +148,7 @@ packagesWithTs.forEach(({packageDir, pkg}) => { ), ); } -}); +} const args = [ 'tsc', diff --git a/scripts/buildUtils.mjs b/scripts/buildUtils.mjs index ab5f4ceaa885..16ff66578952 100644 --- a/scripts/buildUtils.mjs +++ b/scripts/buildUtils.mjs @@ -96,7 +96,7 @@ export function getPackages() { } if (pkg.bin) { - Object.entries(pkg.bin).forEach(([binName, binPath]) => { + for (const [binName, binPath] of Object.entries(pkg.bin)) { const fullBinPath = path.resolve(packageDir, binPath); if (!fs.existsSync(fullBinPath)) { @@ -104,7 +104,7 @@ export function getPackages() { `Binary in package "${pkg.name}" with name "${binName}" at ${binPath} does not exist`, ); } - }); + } } return {packageDir, pkg}; diff --git a/scripts/cleanE2e.mjs b/scripts/cleanE2e.mjs index 1988a916b4d7..61ea7582d2bb 100644 --- a/scripts/cleanE2e.mjs +++ b/scripts/cleanE2e.mjs @@ -29,6 +29,6 @@ const e2eNodeModules = glob.sync('e2e/{*,*/*}/node_modules/', { ignore: excludedModules, }); -e2eNodeModules.forEach(dir => { +for (const dir of e2eNodeModules) { fs.rmSync(dir, {force: true, recursive: true}); -}); +} diff --git a/scripts/mapCoverage.mjs b/scripts/mapCoverage.mjs index 1ce71326b61a..0e536d3c9f12 100644 --- a/scripts/mapCoverage.mjs +++ b/scripts/mapCoverage.mjs @@ -42,12 +42,10 @@ const mapFileCoverage = fileCoverage => { return fileCoverage; }; -Object.keys(coverage).forEach(filename => - map.addFileCoverage(mapFileCoverage(coverage[filename])), -); +for (const filename of Object.keys(coverage)) + map.addFileCoverage(mapFileCoverage(coverage[filename])); const context = istanbulReport.createContext({coverageMap: map}); -['json', 'lcov', 'text'].forEach(reporter => - istanbulReports.create(reporter, {}).execute(context), -); +for (const reporter of ['json', 'lcov', 'text']) + istanbulReports.create(reporter, {}).execute(context); diff --git a/website/src/pages/animations/_landingAnimation.js b/website/src/pages/animations/_landingAnimation.js index fcdab2783baa..4a0d0fe52ee6 100644 --- a/website/src/pages/animations/_landingAnimation.js +++ b/website/src/pages/animations/_landingAnimation.js @@ -26,10 +26,10 @@ export function setupLandingAnimation() { function positionCards() { const handWidth = hand.offsetWidth; - cards.forEach(card => { + for (const card of cards) { const offset = parseInt(card.dataset.index, 10) - 2; card.parentElement.style.transform = cardTransform(offset, handWidth); - }); + } } const results = []; @@ -43,15 +43,15 @@ export function setupLandingAnimation() { } else if (results[index]) { card.classList.remove('jest-card-fail'); card.classList.add('jest-card-pass'); - card.querySelectorAll('.jest-card-label').forEach(el => { + for (const el of card.querySelectorAll('.jest-card-label')) { el.innerHTML = 'PASS'; - }); + } } else { card.classList.remove('jest-card-pass'); card.classList.add('jest-card-fail'); - card.querySelectorAll('.jest-card-label').forEach(el => { + for (const el of card.querySelectorAll('.jest-card-label')) { el.innerHTML = 'FAIL'; - }); + } } }, minTime); @@ -76,7 +76,7 @@ export function setupLandingAnimation() { function forceRun(minTime) { let fails = 0; - cards.forEach((card, index) => { + for (const [index, card] of cards.entries()) { card.classList.add('jest-card-running'); const result = index === 2 || fails > 1 || Math.random() > 0.25; if (!result) { @@ -84,7 +84,7 @@ export function setupLandingAnimation() { } results[index] = result; resolveRun(card, index, minTime); - }); + } } function runTest(card, index) { @@ -162,12 +162,8 @@ export function setupLandingAnimation() { clickButton.text = button.title; clickButton.className = 'button button--primary button--outline landing'; clickButton.onclick = () => { - document - .querySelectorAll('.matchers .button.landing') - .forEach( - b => - (b.className = 'button button--primary button--outline landing') - ); + for (const b of document.querySelectorAll('.matchers .button.landing')) + b.className = 'button button--primary button--outline landing'; clickButton.className = 'button button--primary button--outline landing button--active'; screenshotImg.style.opacity = 0.5; @@ -188,12 +184,12 @@ export function setupLandingAnimation() { // we can't make the screenshots clickable. This fixes that with client-side // JS. Let's call it progressive enhancement, sure. function makeScreenshotsClickable() { - document.querySelectorAll('.blockImage img').forEach(img => { + for (const img of document.querySelectorAll('.blockImage img')) { img.style.cursor = 'pointer'; img.onclick = () => { document.location = img.src; }; - }); + } } let resizeTimeout;