mirror of
https://github.com/hanzoai/jest.git
synced 2026-09-24 16:59:57 +00:00
chore: use for..of instead of forEach (#14517)
This commit is contained in:
@@ -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',
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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 = <T>(
|
||||
): [Array<T>, Array<T>] => {
|
||||
const result: [Array<T>, Array<T>] = [[], []];
|
||||
|
||||
items.forEach(item => result[predicate(item) ? 0 : 1].push(item));
|
||||
for (const item of items) result[predicate(item) ? 0 : 1].push(item);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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 = {};
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -113,7 +113,7 @@ export const expect: Expect = (actual: any, ...rest: Array<any>) => {
|
||||
|
||||
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<any>) => {
|
||||
actual,
|
||||
err,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return expectation;
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
@@ -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 &&
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -196,14 +196,14 @@ export default class SearchSource {
|
||||
|
||||
const collectCoverageFrom = new Set<string>();
|
||||
|
||||
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<string>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,12 +98,12 @@ class TestScheduler {
|
||||
);
|
||||
const timings: Array<number> = [];
|
||||
const testContexts = new Set<TestContext>();
|
||||
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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,6 +182,6 @@ class MockStdin {
|
||||
}
|
||||
|
||||
emit(key: string) {
|
||||
this._callbacks.forEach(cb => cb(key));
|
||||
for (const cb of this._callbacks) cb(key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -156,12 +156,12 @@ export default async function watch(
|
||||
const watchPlugins: Array<WatchPlugin> = 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;
|
||||
|
||||
@@ -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([
|
||||
|
||||
@@ -26,7 +26,7 @@ const countChanges = (diffs: Array<Diff>): 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<Diff>): 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));
|
||||
};
|
||||
|
||||
@@ -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();
|
||||
};
|
||||
|
||||
@@ -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', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -51,7 +51,7 @@ export default function bind<EachCallback extends Global.TestCallback>(
|
||||
? 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<EachCallback extends Global.TestCallback>(
|
||||
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}`);
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -247,14 +247,14 @@ export default class FakeTimers<TimerRef = unknown> {
|
||||
// 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<TimerRef = unknown> {
|
||||
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;
|
||||
|
||||
@@ -203,9 +203,10 @@ export default class FakeTimers {
|
||||
Object.keys(this._fakeTimers.timers) as Array<FakeableAPI>,
|
||||
);
|
||||
|
||||
fakeTimersConfig.doNotFake?.forEach(nameOfFakeableAPI => {
|
||||
toFake.delete(nameOfFakeableAPI);
|
||||
});
|
||||
if (fakeTimersConfig.doNotFake)
|
||||
for (const nameOfFakeableAPI of fakeTimersConfig.doNotFake) {
|
||||
toFake.delete(nameOfFakeableAPI);
|
||||
}
|
||||
|
||||
return {
|
||||
advanceTimeDelta,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -41,22 +41,22 @@ const disabledJasmineMethods: Record<DisabledJasmineMethodsKeys, string> = {
|
||||
export function installErrorOnPrivate(global: Global.Global): void {
|
||||
const jasmine = global.jasmine;
|
||||
|
||||
(Object.keys(disabledGlobals) as Array<DisabledGlobalKeys>).forEach(
|
||||
functionName => {
|
||||
global[functionName] = () => {
|
||||
throwAtFunction(disabledGlobals[functionName], global[functionName]);
|
||||
};
|
||||
},
|
||||
);
|
||||
for (const functionName of Object.keys(
|
||||
disabledGlobals,
|
||||
) as Array<DisabledGlobalKeys>) {
|
||||
global[functionName] = () => {
|
||||
throwAtFunction(disabledGlobals[functionName], global[functionName]);
|
||||
};
|
||||
}
|
||||
|
||||
(
|
||||
Object.keys(disabledJasmineMethods) as Array<DisabledJasmineMethodsKeys>
|
||||
).forEach(methodName => {
|
||||
for (const methodName of Object.keys(
|
||||
disabledJasmineMethods,
|
||||
) as Array<DisabledJasmineMethodsKeys>) {
|
||||
// @ts-expect-error - void unallowd, but it throws 🤷
|
||||
jasmine[methodName] = () => {
|
||||
throwAtFunction(disabledJasmineMethods[methodName], jasmine[methodName]);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function set() {
|
||||
throwAtFunction(
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<unknown>) {
|
||||
// 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);
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -95,12 +95,9 @@ export default async function setupJestGlobals({
|
||||
}: SetupOptions): Promise<SnapshotState> {
|
||||
// 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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]);
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -125,9 +125,9 @@ function deepCyclicCopyMap<T>(
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -462,13 +462,13 @@ export const formatResultsErrors = (
|
||||
): string | null => {
|
||||
const failedResults: FailedResults = testResults.reduce<FailedResults>(
|
||||
(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;
|
||||
},
|
||||
[],
|
||||
|
||||
@@ -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<Function> = [];
|
||||
const refs = {};
|
||||
const mock = this._generateMock<T>(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<T>(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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<void> {
|
||||
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<string> = [];
|
||||
|
||||
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<string, RuntimeTransformResult>();
|
||||
|
||||
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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Array<string>> = [];
|
||||
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<Array<string>> = [];
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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, {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ export default class VerboseReporter extends DefaultReporter {
|
||||
|
||||
static groupTestsBySuites(testResults: Array<AssertionResult>): 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<AssertionResult>, 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<AssertionResult>;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
{
|
||||
|
||||
@@ -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<any> = notify.notify.mock.calls;
|
||||
expect(
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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)};
|
||||
};
|
||||
|
||||
@@ -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<keyof typeof globalThis>).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'},
|
||||
);
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,10 +21,7 @@ const testPath = (names: Array<string>) => {
|
||||
|
||||
// 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);
|
||||
|
||||
@@ -228,7 +228,7 @@ const isAnyOrAnything = (input: object) =>
|
||||
const deepMergeArray = (target: Array<any>, source: Array<any>) => {
|
||||
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<any>, source: Array<any>) => {
|
||||
// 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)) {
|
||||
|
||||
@@ -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<Test>, results: AggregatedResult): void {
|
||||
const map = Object.create(null) as Record<string, Test | undefined>;
|
||||
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) {
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -41,10 +41,10 @@ function deepCyclicCopyObject<T>(
|
||||
|
||||
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<T>(
|
||||
}
|
||||
|
||||
descriptor.configurable = true;
|
||||
});
|
||||
}
|
||||
|
||||
return Object.defineProperties(newObject, descriptors);
|
||||
}
|
||||
|
||||
@@ -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<any>) {
|
||||
// @ts-expect-error: no index
|
||||
return globalThis[dtrace].apply(this, args);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
return Object.assign(globalObject, deepCyclicCopy(globals));
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 =>
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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<unknown> = new Promise(
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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(
|
||||
[
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user