id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
1,700
async (test: Test, testResult: TestResult) => { if (watcher.isInterrupted()) { return Promise.resolve(); } if (testResult.testResults.length === 0) { const message = 'Your test suite must contain at least one test.'; return onFailure(test, { message, stack: new Error(message).stack, }); } // Throws when the context is leaked after executing a test. if (testResult.leaks) { const message = `${chalk.red.bold( 'EXPERIMENTAL FEATURE!\n', )}Your test suite is leaking memory. Please ensure all references are cleaned.\n` + '\n' + 'There is a number of things that can leak memory:\n' + ' - Async operations that have not finished (e.g. fs.readFile).\n' + ' - Timers not properly mocked (e.g. setInterval, setTimeout).\n' + ' - Keeping references to the global scope.'; return onFailure(test, { message, stack: new Error(message).stack, }); } addResult(aggregatedResults, testResult); await this._dispatcher.onTestFileResult( test, testResult, aggregatedResults, ); return this._bailIfNeeded(testContexts, aggregatedResults, watcher); }
type Test = { context: TestContext; duration?: number; path: string; };
1,701
async (test: Test, testResult: TestResult) => { if (watcher.isInterrupted()) { return Promise.resolve(); } if (testResult.testResults.length === 0) { const message = 'Your test suite must contain at least one test.'; return onFailure(test, { message, stack: new Error(message).stack, }); } // Throws when the context is leaked after executing a test. if (testResult.leaks) { const message = `${chalk.red.bold( 'EXPERIMENTAL FEATURE!\n', )}Your test suite is leaking memory. Please ensure all references are cleaned.\n` + '\n' + 'There is a number of things that can leak memory:\n' + ' - Async operations that have not finished (e.g. fs.readFile).\n' + ' - Timers not properly mocked (e.g. setInterval, setTimeout).\n' + ' - Keeping references to the global scope.'; return onFailure(test, { message, stack: new Error(message).stack, }); } addResult(aggregatedResults, testResult); await this._dispatcher.onTestFileResult( test, testResult, aggregatedResults, ); return this._bailIfNeeded(testContexts, aggregatedResults, watcher); }
type Test = (arg0: any) => boolean;
1,702
async (test: Test, testResult: TestResult) => { if (watcher.isInterrupted()) { return Promise.resolve(); } if (testResult.testResults.length === 0) { const message = 'Your test suite must contain at least one test.'; return onFailure(test, { message, stack: new Error(message).stack, }); } // Throws when the context is leaked after executing a test. if (testResult.leaks) { const message = `${chalk.red.bold( 'EXPERIMENTAL FEATURE!\n', )}Your test suite is leaking memory. Please ensure all references are cleaned.\n` + '\n' + 'There is a number of things that can leak memory:\n' + ' - Async operations that have not finished (e.g. fs.readFile).\n' + ' - Timers not properly mocked (e.g. setInterval, setTimeout).\n' + ' - Keeping references to the global scope.'; return onFailure(test, { message, stack: new Error(message).stack, }); } addResult(aggregatedResults, testResult); await this._dispatcher.onTestFileResult( test, testResult, aggregatedResults, ); return this._bailIfNeeded(testContexts, aggregatedResults, watcher); }
type TestResult = { console?: ConsoleBuffer; coverage?: CoverageMapData; displayName?: Config.DisplayName; failureMessage?: string | null; leaks: boolean; memoryUsage?: number; numFailingTests: number; numPassingTests: number; numPendingTests: number; numTodoTests: number; openHandles: Array<Error>; perfStats: { end: number; runtime: number; slow: boolean; start: number; }; skipped: boolean; snapshot: { added: number; fileDeleted: boolean; matched: number; unchecked: number; uncheckedKeys: Array<string>; unmatched: number; updated: number; }; testExecError?: SerializableError; testFilePath: string; testResults: Array<AssertionResult>; v8Coverage?: V8CoverageResult; };
1,703
async (test: Test, testResult: TestResult) => { if (watcher.isInterrupted()) { return Promise.resolve(); } if (testResult.testResults.length === 0) { const message = 'Your test suite must contain at least one test.'; return onFailure(test, { message, stack: new Error(message).stack, }); } // Throws when the context is leaked after executing a test. if (testResult.leaks) { const message = `${chalk.red.bold( 'EXPERIMENTAL FEATURE!\n', )}Your test suite is leaking memory. Please ensure all references are cleaned.\n` + '\n' + 'There is a number of things that can leak memory:\n' + ' - Async operations that have not finished (e.g. fs.readFile).\n' + ' - Timers not properly mocked (e.g. setInterval, setTimeout).\n' + ' - Keeping references to the global scope.'; return onFailure(test, { message, stack: new Error(message).stack, }); } addResult(aggregatedResults, testResult); await this._dispatcher.onTestFileResult( test, testResult, aggregatedResults, ); return this._bailIfNeeded(testContexts, aggregatedResults, watcher); }
type TestResult = { duration?: number | null; errors: Array<FormattedError>; errorsDetailed: Array<MatcherResults | unknown>; invocations: number; status: TestStatus; location?: {column: number; line: number} | null; numPassingAsserts: number; retryReasons: Array<FormattedError>; testPath: Array<TestName | BlockName>; };
1,704
async (test: Test, error: SerializableError) => { if (watcher.isInterrupted()) { return; } const testResult = buildFailureTestResult(test.path, error); testResult.failureMessage = formatExecError( testResult.testExecError, test.context.config, this._globalConfig, test.path, ); addResult(aggregatedResults, testResult); await this._dispatcher.onTestFileResult( test, testResult, aggregatedResults, ); }
type Test = { context: TestContext; duration?: number; path: string; };
1,705
async (test: Test, error: SerializableError) => { if (watcher.isInterrupted()) { return; } const testResult = buildFailureTestResult(test.path, error); testResult.failureMessage = formatExecError( testResult.testExecError, test.context.config, this._globalConfig, test.path, ); addResult(aggregatedResults, testResult); await this._dispatcher.onTestFileResult( test, testResult, aggregatedResults, ); }
type Test = (arg0: any) => boolean;
1,706
async (test: Test, error: SerializableError) => { if (watcher.isInterrupted()) { return; } const testResult = buildFailureTestResult(test.path, error); testResult.failureMessage = formatExecError( testResult.testExecError, test.context.config, this._globalConfig, test.path, ); addResult(aggregatedResults, testResult); await this._dispatcher.onTestFileResult( test, testResult, aggregatedResults, ); }
type SerializableError = TestResult.SerializableError;
1,707
async (test: Test, error: SerializableError) => { if (watcher.isInterrupted()) { return; } const testResult = buildFailureTestResult(test.path, error); testResult.failureMessage = formatExecError( testResult.testExecError, test.context.config, this._globalConfig, test.path, ); addResult(aggregatedResults, testResult); await this._dispatcher.onTestFileResult( test, testResult, aggregatedResults, ); }
type SerializableError = { code?: unknown; message: string; stack: string | null | undefined; type?: string; };
1,708
function getNoTestFoundVerbose( testRunData: TestRunData, globalConfig: Config.GlobalConfig, willExitWith0: boolean, ): string { const individualResults = testRunData.map(testRun => { const stats = testRun.matches.stats || ({} as Stats); const config = testRun.context.config; const statsMessage = (Object.keys(stats) as Array<keyof Stats>) .map(key => { if (key === 'roots' && config.roots.length === 1) { return null; } const value = (config as Record<string, unknown>)[key]; if (value) { const valueAsString = Array.isArray(value) ? value.join(', ') : String(value); const matches = pluralize('match', stats[key] || 0, 'es'); return ` ${key}: ${chalk.yellow(valueAsString)} - ${matches}`; } return null; }) .filter(line => line) .join('\n'); return testRun.matches.total ? `In ${chalk.bold(config.rootDir)}\n` + ` ${pluralize( 'file', testRun.matches.total || 0, 's', )} checked.\n${statsMessage}` : `No files found in ${config.rootDir}.\n` + "Make sure Jest's configuration does not exclude this directory." + '\nTo set up Jest, make sure a package.json file exists.\n' + 'Jest Documentation: ' + 'https://jestjs.io/docs/configuration'; }); let dataMessage; if (globalConfig.runTestsByPath) { dataMessage = `Files: ${globalConfig.nonFlagArgs .map(p => `"${p}"`) .join(', ')}`; } else { dataMessage = `Pattern: ${chalk.yellow( globalConfig.testPathPattern, )} - 0 matches`; } if (willExitWith0) { return `${chalk.bold( 'No tests found, exiting with code 0', )}\n${individualResults.join('\n')}\n${dataMessage}`; } return ( `${chalk.bold('No tests found, exiting with code 1')}\n` + 'Run with `--passWithNoTests` to exit with code 0' + `\n${individualResults.join('\n')}\n${dataMessage}` ); }
type TestRunData = Array<{ context: TestContext; matches: { allTests: number; tests: Array<Test>; total?: number; stats?: Stats; }; }>;
1,709
(failure?: AssertionLocation) => void
type AssertionLocation = { fullName: string; path: string; };
1,710
updateWithResults(results: AggregatedResult): void { if (!results.snapshot.failure && results.numFailedTests > 0) { return this._drawUIOverlay(); } this._testAssertions.shift(); if (this._testAssertions.length === 0) { return this._drawUIOverlay(); } // Go to the next test return this._run(); }
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,711
updateWithResults(results: AggregatedResult): void { const hasSnapshotFailure = !!results.snapshot.failure; if (hasSnapshotFailure) { this._drawUIOverlay(); return; } this._testAssertions.shift(); if (this._testAssertions.length - this._skippedNum === 0) { this._drawUIOverlay(); return; } // Go to the next test this._run(false); }
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,712
function getNoTestsFoundMessage( testRunData: TestRunData, globalConfig: Config.GlobalConfig, ): {exitWith0: boolean; message: string} { const exitWith0 = globalConfig.passWithNoTests || globalConfig.lastCommit || globalConfig.onlyChanged; if (globalConfig.onlyFailures) { return {exitWith0, message: getNoTestFoundFailed(globalConfig)}; } if (globalConfig.onlyChanged) { return { exitWith0, message: getNoTestFoundRelatedToChangedFiles(globalConfig), }; } if (globalConfig.passWithNoTests) { return {exitWith0, message: getNoTestFoundPassWithNoTests()}; } return { exitWith0, message: testRunData.length === 1 || globalConfig.verbose ? getNoTestFoundVerbose(testRunData, globalConfig, exitWith0) : getNoTestFound(testRunData, globalConfig, exitWith0), }; }
type TestRunData = Array<{ context: TestContext; matches: { allTests: number; tests: Array<Test>; total?: number; stats?: Stats; }; }>;
1,713
(context: TestContext, tests: Array<string>) => tests.map(path => ({ context, duration: undefined, path, }))
type TestContext = { config: Config.ProjectConfig; hasteFS: IHasteFS; moduleMap: IModuleMap; resolver: Resolver; };
1,714
(context: TestContext, tests: Array<string>) => tests.map(path => ({ context, duration: undefined, path, }))
type TestContext = Record<string, unknown>;
1,715
(context: TestContext, tests: Array<string>) => tests.map(path => ({ context, duration: undefined, path, }))
type TestContext = Global.TestContext;
1,716
(changedFilesInfo: ChangedFiles) => { const {repos} = changedFilesInfo; // no SCM (git/hg/...) is found in any of the roots. const noSCM = Object.values(repos).every(scm => scm.size === 0); return !noSCM; }
type ChangedFiles = {repos: Repos; changedFiles: Paths};
1,717
constructor(context: TestContext) { const {config} = context; this._context = context; this._dependencyResolver = null; const rootPattern = new RegExp( config.roots.map(dir => escapePathForRegex(dir + path.sep)).join('|'), ); this._testPathCases.push({ isMatch: path => rootPattern.test(path), stat: 'roots', }); if (config.testMatch.length) { this._testPathCases.push({ isMatch: globsToMatcher(config.testMatch), stat: 'testMatch', }); } if (config.testPathIgnorePatterns.length) { const testIgnorePatternsRegex = new RegExp( config.testPathIgnorePatterns.join('|'), ); this._testPathCases.push({ isMatch: path => !testIgnorePatternsRegex.test(path), stat: 'testPathIgnorePatterns', }); } if (config.testRegex.length) { this._testPathCases.push({ isMatch: regexToMatcher(config.testRegex), stat: 'testRegex', }); } }
type TestContext = { config: Config.ProjectConfig; hasteFS: IHasteFS; moduleMap: IModuleMap; resolver: Resolver; };
1,718
constructor(context: TestContext) { const {config} = context; this._context = context; this._dependencyResolver = null; const rootPattern = new RegExp( config.roots.map(dir => escapePathForRegex(dir + path.sep)).join('|'), ); this._testPathCases.push({ isMatch: path => rootPattern.test(path), stat: 'roots', }); if (config.testMatch.length) { this._testPathCases.push({ isMatch: globsToMatcher(config.testMatch), stat: 'testMatch', }); } if (config.testPathIgnorePatterns.length) { const testIgnorePatternsRegex = new RegExp( config.testPathIgnorePatterns.join('|'), ); this._testPathCases.push({ isMatch: path => !testIgnorePatternsRegex.test(path), stat: 'testPathIgnorePatterns', }); } if (config.testRegex.length) { this._testPathCases.push({ isMatch: regexToMatcher(config.testRegex), stat: 'testRegex', }); } }
type TestContext = Record<string, unknown>;
1,719
constructor(context: TestContext) { const {config} = context; this._context = context; this._dependencyResolver = null; const rootPattern = new RegExp( config.roots.map(dir => escapePathForRegex(dir + path.sep)).join('|'), ); this._testPathCases.push({ isMatch: path => rootPattern.test(path), stat: 'roots', }); if (config.testMatch.length) { this._testPathCases.push({ isMatch: globsToMatcher(config.testMatch), stat: 'testMatch', }); } if (config.testPathIgnorePatterns.length) { const testIgnorePatternsRegex = new RegExp( config.testPathIgnorePatterns.join('|'), ); this._testPathCases.push({ isMatch: path => !testIgnorePatternsRegex.test(path), stat: 'testPathIgnorePatterns', }); } if (config.testRegex.length) { this._testPathCases.push({ isMatch: regexToMatcher(config.testRegex), stat: 'testRegex', }); } }
type TestContext = Global.TestContext;
1,720
async findTestRelatedToChangedFiles( changedFilesInfo: ChangedFiles, collectCoverage: boolean, ): Promise<SearchResult> { if (!hasSCM(changedFilesInfo)) { return {noSCM: true, tests: []}; } const {changedFiles} = changedFilesInfo; return this.findRelatedTests(changedFiles, collectCoverage); }
type ChangedFiles = {repos: Repos; changedFiles: Paths};
1,721
async findRelatedSourcesFromTestsInChangedFiles( changedFilesInfo: ChangedFiles, ): Promise<Array<string>> { if (!hasSCM(changedFilesInfo)) { return []; } const {changedFiles} = changedFilesInfo; const dependencyResolver = await this._getOrBuildDependencyResolver(); const relatedSourcesSet = new Set<string>(); changedFiles.forEach(filePath => { if (this.isTestFilePath(filePath)) { const sourcePaths = dependencyResolver.resolve(filePath, { skipNodeResolution: this._context.config.skipNodeResolution, }); sourcePaths.forEach(sourcePath => relatedSourcesSet.add(sourcePath)); } }); return Array.from(relatedSourcesSet); }
type ChangedFiles = {repos: Repos; changedFiles: Paths};
1,722
function getNoTestFound( testRunData: TestRunData, globalConfig: Config.GlobalConfig, willExitWith0: boolean, ): string { const testFiles = testRunData.reduce( (current, testRun) => current + (testRun.matches.total || 0), 0, ); let dataMessage; if (globalConfig.runTestsByPath) { dataMessage = `Files: ${globalConfig.nonFlagArgs .map(p => `"${p}"`) .join(', ')}`; } else { dataMessage = `Pattern: ${chalk.yellow( globalConfig.testPathPattern, )} - 0 matches`; } if (willExitWith0) { return ( `${chalk.bold('No tests found, exiting with code 0')}\n` + `In ${chalk.bold(globalConfig.rootDir)}` + '\n' + ` ${pluralize('file', testFiles, 's')} checked across ${pluralize( 'project', testRunData.length, 's', )}. Run with \`--verbose\` for more details.` + `\n${dataMessage}` ); } return ( `${chalk.bold('No tests found, exiting with code 1')}\n` + 'Run with `--passWithNoTests` to exit with code 0' + '\n' + `In ${chalk.bold(globalConfig.rootDir)}` + '\n' + ` ${pluralize('file', testFiles, 's')} checked across ${pluralize( 'project', testRunData.length, 's', )}. Run with \`--verbose\` for more details.` + `\n${dataMessage}` ); }
type TestRunData = Array<{ context: TestContext; matches: { allTests: number; tests: Array<Test>; total?: number; stats?: Stats; }; }>;
1,723
(results: AggregatedResult) => void | undefined
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,724
override apply(hooks: JestHookSubscriber): void { hooks.onTestRunComplete(results => { this._failedTestAssertions = this.getFailedTestAssertions(results); if (this._manager.isActive()) this._manager.updateWithResults(results); }); }
type JestHookSubscriber = { onFileChange: (fn: FileChange) => void; onTestRunComplete: (fn: TestRunComplete) => void; shouldRunTestSuite: (fn: ShouldRunTestSuite) => void; };
1,725
private getFailedTestAssertions( results: AggregatedResult, ): Array<AssertionLocation> { const failedTestPaths: Array<AssertionLocation> = []; if ( // skip if no failed tests results.numFailedTests === 0 || // skip if missing test results !results.testResults || // skip if unmatched snapshots are present results.snapshot.unmatched ) { return failedTestPaths; } results.testResults.forEach(testResult => { testResult.testResults.forEach(result => { if (result.status === 'failed') { failedTestPaths.push({ fullName: result.fullName, path: testResult.testFilePath, }); } }); }); return failedTestPaths; }
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,726
getFailedSnapshotTestAssertions( testResults: AggregatedResult, ): Array<AssertionLocation> { const failedTestPaths: Array<AssertionLocation> = []; if (testResults.numFailedTests === 0 || !testResults.testResults) { return failedTestPaths; } testResults.testResults.forEach(testResult => { if (testResult.snapshot && testResult.snapshot.unmatched) { testResult.testResults.forEach(result => { if (result.status === 'failed') { failedTestPaths.push({ fullName: result.fullName, path: testResult.testFilePath, }); } }); } }); return failedTestPaths; }
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,727
override apply(hooks: JestHookSubscriber): void { hooks.onTestRunComplete(results => { this._failedSnapshotTestAssertions = this.getFailedSnapshotTestAssertions(results); if (this._snapshotInteractiveMode.isActive()) { this._snapshotInteractiveMode.updateWithResults(results); } }); }
type JestHookSubscriber = { onFileChange: (fn: FileChange) => void; onTestRunComplete: (fn: TestRunComplete) => void; shouldRunTestSuite: (fn: ShouldRunTestSuite) => void; };
1,728
override apply(hooks: JestHookSubscriber): void { hooks.onTestRunComplete(results => { this._hasSnapshotFailure = results.snapshot.failure; }); }
type JestHookSubscriber = { onFileChange: (fn: FileChange) => void; onTestRunComplete: (fn: TestRunComplete) => void; shouldRunTestSuite: (fn: ShouldRunTestSuite) => void; };
1,729
(a: WatchPlugin, b: WatchPlugin) => { if (a.isInternal && b.isInternal) { // internal plugins in the order we specify them return 0; } if (a.isInternal !== b.isInternal) { // external plugins afterwards return a.isInternal ? -1 : 1; } const usageInfoA = a.getUsageInfo && a.getUsageInfo(globalConfig); const usageInfoB = b.getUsageInfo && b.getUsageInfo(globalConfig); if (usageInfoA && usageInfoB) { // external plugins in alphabetical order return usageInfoA.key.localeCompare(usageInfoB.key); } return 0; }
interface WatchPlugin { isInternal?: boolean; apply?: (hooks: JestHookSubscriber) => void; getUsageInfo?: (globalConfig: Config.GlobalConfig) => UsageData | null; onKey?: (value: string) => void; run?: ( globalConfig: Config.GlobalConfig, updateConfigAndRun: UpdateConfigCallback, ) => Promise<void | boolean>; }
1,730
( this: Context, actual: unknown, ...expected: Expected ) => ExpectationResult
type Context = { object: unknown; args: Array<unknown>; returnValue?: unknown; };
1,731
( this: Context, actual: unknown, ...expected: Expected ) => ExpectationResult
interface Context extends MatcherContext { snapshotState: SnapshotState; }
1,732
(this: Context, actual: any, ...expected: Array<any>): ExpectationResult
type Context = { object: unknown; args: Array<unknown>; returnValue?: unknown; };
1,733
(this: Context, actual: any, ...expected: Array<any>): ExpectationResult
interface Context extends MatcherContext { snapshotState: SnapshotState; }
1,734
extend(matchers: MatchersObject): void
type MatchersObject = { [name: string]: RawMatcherFn; };
1,735
function ( matcher: RawMatcherFn, ) { return function ( this: MatcherContext, received: any, testNameOrInlineSnapshot?: string, ) { return matcher.apply(this, [received, testNameOrInlineSnapshot, true]); }; }
type RawMatcherFn<Context extends MatcherContext = MatcherContext> = { (this: Context, actual: any, ...expected: Array<any>): ExpectationResult; /** @internal */ [INTERNAL_MATCHER_FLAG]?: boolean; };
1,736
function ( this: MatcherContext, received: any, testNameOrInlineSnapshot?: string, ) { return matcher.apply(this, [received, testNameOrInlineSnapshot, true]); }
type MatcherContext = MatcherUtils & Readonly<MatcherState>;
1,737
( matcher: RawMatcherFn, isNot: boolean, promise: string, actual: any, err?: JestAssertionError, ): ThrowingMatcherFn => function throwingMatcher(...args): any { let throws = true; const utils: MatcherUtils['utils'] = { ...matcherUtils, iterableEquality, subsetEquality, }; const matcherUtilsThing: MatcherUtils = { customTesters: getCustomEqualityTesters(), // When throws is disabled, the matcher will not throw errors during test // execution but instead add them to the global matcher state. If a // matcher throws, test execution is normally stopped immediately. The // snapshot matcher uses it because we want to log all snapshot // failures in a test. dontThrow: () => (throws = false), equals, utils, }; const matcherContext: MatcherContext = { ...getState<MatcherState>(), ...matcherUtilsThing, error: err, isNot, promise, }; const processResult = ( result: SyncExpectationResult, asyncError?: JestAssertionError, ) => { _validateResult(result); getState().assertionCalls++; if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR const message = getMessage(result.message); let error; if (err) { error = err; error.message = message; } else if (asyncError) { error = asyncError; error.message = message; } else { error = new JestAssertionError(message); // Try to remove this function from the stack trace frame. // Guard for some environments (browsers) that do not support this feature. if (Error.captureStackTrace) { Error.captureStackTrace(error, throwingMatcher); } } // Passing the result of the matcher with the error so that a custom // reporter could access the actual and expected objects of the result // for example in order to display a custom visual diff error.matcherResult = {...result, message}; if (throws) { throw error; } else { getState().suppressedErrors.push(error); } } else { getState().numPassingAsserts++; } }; const handleError = (error: Error) => { if ( matcher[INTERNAL_MATCHER_FLAG] === true && !(error instanceof JestAssertionError) && error.name !== 'PrettyFormatPluginError' && // Guard for some environments (browsers) that do not support this feature. Error.captureStackTrace ) { // Try to remove this and deeper functions from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); } throw error; }; let potentialResult: ExpectationResult; try { potentialResult = matcher[INTERNAL_MATCHER_FLAG] === true ? matcher.call(matcherContext, actual, ...args) : // It's a trap specifically for inline snapshot to capture this name // in the stack trace, so that it can correctly get the custom matcher // function call. (function __EXTERNAL_MATCHER_TRAP__() { return matcher.call(matcherContext, actual, ...args); })(); if (isPromise(potentialResult)) { const asyncError = new JestAssertionError(); if (Error.captureStackTrace) { Error.captureStackTrace(asyncError, throwingMatcher); } return potentialResult .then(aResult => processResult(aResult, asyncError)) .catch(handleError); } else { return processResult(potentialResult); } } catch (error: any) { return handleError(error); } }
type RawMatcherFn<Context extends MatcherContext = MatcherContext> = { (this: Context, actual: any, ...expected: Array<any>): ExpectationResult; /** @internal */ [INTERNAL_MATCHER_FLAG]?: boolean; };
1,738
( matcher: RawMatcherFn, isNot: boolean, promise: string, actual: any, err?: JestAssertionError, ): ThrowingMatcherFn => function throwingMatcher(...args): any { let throws = true; const utils: MatcherUtils['utils'] = { ...matcherUtils, iterableEquality, subsetEquality, }; const matcherUtilsThing: MatcherUtils = { customTesters: getCustomEqualityTesters(), // When throws is disabled, the matcher will not throw errors during test // execution but instead add them to the global matcher state. If a // matcher throws, test execution is normally stopped immediately. The // snapshot matcher uses it because we want to log all snapshot // failures in a test. dontThrow: () => (throws = false), equals, utils, }; const matcherContext: MatcherContext = { ...getState<MatcherState>(), ...matcherUtilsThing, error: err, isNot, promise, }; const processResult = ( result: SyncExpectationResult, asyncError?: JestAssertionError, ) => { _validateResult(result); getState().assertionCalls++; if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR const message = getMessage(result.message); let error; if (err) { error = err; error.message = message; } else if (asyncError) { error = asyncError; error.message = message; } else { error = new JestAssertionError(message); // Try to remove this function from the stack trace frame. // Guard for some environments (browsers) that do not support this feature. if (Error.captureStackTrace) { Error.captureStackTrace(error, throwingMatcher); } } // Passing the result of the matcher with the error so that a custom // reporter could access the actual and expected objects of the result // for example in order to display a custom visual diff error.matcherResult = {...result, message}; if (throws) { throw error; } else { getState().suppressedErrors.push(error); } } else { getState().numPassingAsserts++; } }; const handleError = (error: Error) => { if ( matcher[INTERNAL_MATCHER_FLAG] === true && !(error instanceof JestAssertionError) && error.name !== 'PrettyFormatPluginError' && // Guard for some environments (browsers) that do not support this feature. Error.captureStackTrace ) { // Try to remove this and deeper functions from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); } throw error; }; let potentialResult: ExpectationResult; try { potentialResult = matcher[INTERNAL_MATCHER_FLAG] === true ? matcher.call(matcherContext, actual, ...args) : // It's a trap specifically for inline snapshot to capture this name // in the stack trace, so that it can correctly get the custom matcher // function call. (function __EXTERNAL_MATCHER_TRAP__() { return matcher.call(matcherContext, actual, ...args); })(); if (isPromise(potentialResult)) { const asyncError = new JestAssertionError(); if (Error.captureStackTrace) { Error.captureStackTrace(asyncError, throwingMatcher); } return potentialResult .then(aResult => processResult(aResult, asyncError)) .catch(handleError); } else { return processResult(potentialResult); } } catch (error: any) { return handleError(error); } }
class JestAssertionError extends Error { matcherResult?: Omit<SyncExpectationResult, 'message'> & {message: string}; }
1,739
( result: SyncExpectationResult, asyncError?: JestAssertionError, ) => { _validateResult(result); getState().assertionCalls++; if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR const message = getMessage(result.message); let error; if (err) { error = err; error.message = message; } else if (asyncError) { error = asyncError; error.message = message; } else { error = new JestAssertionError(message); // Try to remove this function from the stack trace frame. // Guard for some environments (browsers) that do not support this feature. if (Error.captureStackTrace) { Error.captureStackTrace(error, throwingMatcher); } } // Passing the result of the matcher with the error so that a custom // reporter could access the actual and expected objects of the result // for example in order to display a custom visual diff error.matcherResult = {...result, message}; if (throws) { throw error; } else { getState().suppressedErrors.push(error); } } else { getState().numPassingAsserts++; } }
type SyncExpectationResult = { pass: boolean; message(): string; };
1,740
( result: SyncExpectationResult, asyncError?: JestAssertionError, ) => { _validateResult(result); getState().assertionCalls++; if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR const message = getMessage(result.message); let error; if (err) { error = err; error.message = message; } else if (asyncError) { error = asyncError; error.message = message; } else { error = new JestAssertionError(message); // Try to remove this function from the stack trace frame. // Guard for some environments (browsers) that do not support this feature. if (Error.captureStackTrace) { Error.captureStackTrace(error, throwingMatcher); } } // Passing the result of the matcher with the error so that a custom // reporter could access the actual and expected objects of the result // for example in order to display a custom visual diff error.matcherResult = {...result, message}; if (throws) { throw error; } else { getState().suppressedErrors.push(error); } } else { getState().numPassingAsserts++; } }
class JestAssertionError extends Error { matcherResult?: Omit<SyncExpectationResult, 'message'> & {message: string}; }
1,741
(matchers: MatchersObject) => setMatchers(matchers, false, expect)
type MatchersObject = { [name: string]: RawMatcherFn; };
1,742
( matchers: MatchersObject, isInternal: boolean, expect: Expect, ): void => { Object.keys(matchers).forEach(key => { const matcher = matchers[key]; if (typeof matcher !== 'function') { throw new TypeError( `expect.extend: \`${key}\` is not a valid matcher. Must be a function, is "${getType( matcher, )}"`, ); } Object.defineProperty(matcher, INTERNAL_MATCHER_FLAG, { value: isInternal, }); if (!isInternal) { // expect is defined class CustomMatcher extends AsymmetricMatcher< [unknown, ...Array<unknown>] > { constructor(inverse = false, ...sample: [unknown, ...Array<unknown>]) { super(sample, inverse); } asymmetricMatch(other: unknown) { const {pass} = matcher.call( this.getMatcherContext(), other, ...this.sample, ) as SyncExpectationResult; return this.inverse ? !pass : pass; } toString() { return `${this.inverse ? 'not.' : ''}${key}`; } override getExpectedType() { return 'any'; } override toAsymmetricMatcher() { return `${this.toString()}<${this.sample.map(String).join(', ')}>`; } } Object.defineProperty(expect, key, { configurable: true, enumerable: true, value: (...sample: [unknown, ...Array<unknown>]) => new CustomMatcher(false, ...sample), writable: true, }); Object.defineProperty(expect.not, key, { configurable: true, enumerable: true, value: (...sample: [unknown, ...Array<unknown>]) => new CustomMatcher(true, ...sample), writable: true, }); } }); Object.assign((globalThis as any)[JEST_MATCHERS_OBJECT].matchers, matchers); }
type MatchersObject = { [name: string]: RawMatcherFn; };
1,743
( matchers: MatchersObject, isInternal: boolean, expect: Expect, ): void => { Object.keys(matchers).forEach(key => { const matcher = matchers[key]; if (typeof matcher !== 'function') { throw new TypeError( `expect.extend: \`${key}\` is not a valid matcher. Must be a function, is "${getType( matcher, )}"`, ); } Object.defineProperty(matcher, INTERNAL_MATCHER_FLAG, { value: isInternal, }); if (!isInternal) { // expect is defined class CustomMatcher extends AsymmetricMatcher< [unknown, ...Array<unknown>] > { constructor(inverse = false, ...sample: [unknown, ...Array<unknown>]) { super(sample, inverse); } asymmetricMatch(other: unknown) { const {pass} = matcher.call( this.getMatcherContext(), other, ...this.sample, ) as SyncExpectationResult; return this.inverse ? !pass : pass; } toString() { return `${this.inverse ? 'not.' : ''}${key}`; } override getExpectedType() { return 'any'; } override toAsymmetricMatcher() { return `${this.toString()}<${this.sample.map(String).join(', ')}>`; } } Object.defineProperty(expect, key, { configurable: true, enumerable: true, value: (...sample: [unknown, ...Array<unknown>]) => new CustomMatcher(false, ...sample), writable: true, }); Object.defineProperty(expect.not, key, { configurable: true, enumerable: true, value: (...sample: [unknown, ...Array<unknown>]) => new CustomMatcher(true, ...sample), writable: true, }); } }); Object.assign((globalThis as any)[JEST_MATCHERS_OBJECT].matchers, matchers); }
type Expect = { <T = unknown>(actual: T): Matchers<void, T> & Inverse<Matchers<void, T>> & PromiseMatchers<T>; } & BaseExpect & AsymmetricMatchers & Inverse<Omit<AsymmetricMatchers, 'any' | 'anything'>>;
1,744
toContainEqual(received: ContainIterable, expected: unknown) { const matcherName = 'toContainEqual'; const isNot = this.isNot; const options: MatcherHintOptions = { comment: 'deep equality', isNot, promise: this.promise, }; if (received == null) { throw new Error( matcherErrorMessage( matcherHint(matcherName, undefined, undefined, options), `${RECEIVED_COLOR('received')} value must not be null nor undefined`, printWithType('Received', received, printReceived), ), ); } const index = Array.from(received).findIndex(item => equals(item, expected, [...this.customTesters, iterableEquality]), ); const pass = index !== -1; const message = () => { const labelExpected = 'Expected value'; const labelReceived = `Received ${getType(received)}`; const printLabel = getLabelPrinter(labelExpected, labelReceived); return ( // eslint-disable-next-line prefer-template matcherHint(matcherName, undefined, undefined, options) + '\n\n' + `${printLabel(labelExpected)}${isNot ? 'not ' : ''}${printExpected( expected, )}\n` + `${printLabel(labelReceived)}${isNot ? ' ' : ''}${ isNot && Array.isArray(received) ? printReceivedArrayContainExpectedItem(received, index) : printReceived(received) }` ); }; return {message, pass}; }
type ContainIterable = | Array<unknown> | Set<unknown> | NodeListOf<Node> | DOMTokenList | HTMLCollectionOf<any>;
1,745
toEqualBook(expected: Book): R
class Book { public name: string; public authors: Array<Author>; public [CONNECTION_PROP]: DbConnection; constructor(name: string, authors: Array<Author>) { this.name = name; this.authors = authors; this[CONNECTION_PROP] = DbConnectionId++; } }
1,746
toEqualBook(expected: Book, actual: Book) { const result = this.equals(expected, actual, this.customTesters); return { message: () => `Expected Book object: ${expected.name}. Actual Book object: ${actual.name}`, pass: result, }; }
class Book { public name: string; public authors: Array<Author>; public [CONNECTION_PROP]: DbConnection; constructor(name: string, authors: Array<Author>) { this.name = name; this.authors = authors; this[CONNECTION_PROP] = DbConnectionId++; } }
1,747
equals(other: Volume): boolean { if (this.unit === other.unit) { return this.amount === other.amount; } else if (this.unit === 'L' && other.unit === 'mL') { return this.amount * 1000 === other.amount; } else { return this.amount === other.amount * 1000; } }
class Volume { public amount: number; public unit: 'L' | 'mL'; constructor(amount: number, unit: 'L' | 'mL') { this.amount = amount; this.unit = unit; } toString(): string { return `[Volume ${this.amount}${this.unit}]`; } equals(other: Volume): boolean { if (this.unit === other.unit) { return this.amount === other.amount; } else if (this.unit === 'L' && other.unit === 'mL') { return this.amount * 1000 === other.amount; } else { return this.amount === other.amount * 1000; } } }
1,748
toEqualVolume(expected: Volume): R
class Volume { public amount: number; public unit: 'L' | 'mL'; constructor(amount: number, unit: 'L' | 'mL') { this.amount = amount; this.unit = unit; } toString(): string { return `[Volume ${this.amount}${this.unit}]`; } equals(other: Volume): boolean { if (this.unit === other.unit) { return this.amount === other.amount; } else if (this.unit === 'L' && other.unit === 'mL') { return this.amount * 1000 === other.amount; } else { return this.amount === other.amount * 1000; } } }
1,749
toEqualVolume(expected: Volume, actual: Volume) { const result = this.equals(expected, actual, this.customTesters); return { message: () => `Expected Volume object: ${expected.toString()}. Actual Volume object: ${actual.toString()}`, pass: result, }; }
class Volume { public amount: number; public unit: 'L' | 'mL'; constructor(amount: number, unit: 'L' | 'mL') { this.amount = amount; this.unit = unit; } toString(): string { return `[Volume ${this.amount}${this.unit}]`; } equals(other: Volume): boolean { if (this.unit === other.unit) { return this.amount === other.amount; } else if (this.unit === 'L' && other.unit === 'mL') { return this.amount * 1000 === other.amount; } else { return this.amount === other.amount * 1000; } } }
1,750
( this: MatcherContext, actual: unknown, floor: number, ceiling: number, ) => any
type MatcherContext = MatcherUtils & Readonly<MatcherState>;
1,751
(this: MatcherContext, actual: unknown) => any
type MatcherContext = MatcherUtils & Readonly<MatcherState>;
1,752
( this: CustomContext, actual: unknown, count: number, ) => any
interface CustomContext extends MatcherContext { customMethod(): void; }
1,753
( this: TestContext, done: DoneFn, ) => ValidTestReturnValues
type TestContext = { config: Config.ProjectConfig; hasteFS: IHasteFS; moduleMap: IModuleMap; resolver: Resolver; };
1,754
( this: TestContext, done: DoneFn, ) => ValidTestReturnValues
type TestContext = Record<string, unknown>;
1,755
( this: TestContext, done: DoneFn, ) => ValidTestReturnValues
type TestContext = Global.TestContext;
1,756
( this: TestContext, done: DoneFn, ) => ValidTestReturnValues
interface DoneFn { (error?: any): void; fail: (error: Error) => void; }
1,757
( this: TestContext, done: DoneFn, ) => ValidTestReturnValues
type DoneFn = (reason?: string | Error) => void;
1,758
( this: TestContext, done: DoneFn, ) => ValidTestReturnValues
type DoneFn = Global.DoneFn;
1,759
(this: TestContext) => TestReturnValue
type TestContext = { config: Config.ProjectConfig; hasteFS: IHasteFS; moduleMap: IModuleMap; resolver: Resolver; };
1,760
(this: TestContext) => TestReturnValue
type TestContext = Record<string, unknown>;
1,761
(this: TestContext) => TestReturnValue
type TestContext = Global.TestContext;
1,762
( this: TestContext, ) => TestReturnValueGenerator
type TestContext = { config: Config.ProjectConfig; hasteFS: IHasteFS; moduleMap: IModuleMap; resolver: Resolver; };
1,763
( this: TestContext, ) => TestReturnValueGenerator
type TestContext = Record<string, unknown>;
1,764
( this: TestContext, ) => TestReturnValueGenerator
type TestContext = Global.TestContext;
1,765
(arg: T, done: DoneFn) => ReturnType<EachFn>
interface DoneFn { (error?: any): void; fail: (error: Error) => void; }
1,766
(arg: T, done: DoneFn) => ReturnType<EachFn>
type DoneFn = (reason?: string | Error) => void;
1,767
(arg: T, done: DoneFn) => ReturnType<EachFn>
type DoneFn = Global.DoneFn;
1,768
(fn: HookFn, timeout?: number): void
type HookFn = TestFn;
1,769
(fn: HookFn, timeout?: number): void
type HookFn = Global.HookFn;
1,770
(testName: TestNameLike, fn: T, timeout?: number): void
type TestNameLike = TestName | NameLike;
1,771
(testName: TestNameLike, fn: T, timeout?: number): void
type TestNameLike = Global.TestNameLike;
1,772
(testName: TestNameLike, fn: TestFn, timeout?: number): void
type TestNameLike = TestName | NameLike;
1,773
(testName: TestNameLike, fn: TestFn, timeout?: number): void
type TestNameLike = Global.TestNameLike;
1,774
(testName: TestNameLike, fn: TestFn, timeout?: number): void
type TestFn = | PromiseReturningTestFn | GeneratorReturningTestFn | DoneTakingTestFn;
1,775
(testName: TestNameLike, fn: TestFn, timeout?: number): void
type TestFn = Global.TestFn;
1,776
(testName: TestNameLike) => void
type TestNameLike = TestName | NameLike;
1,777
(testName: TestNameLike) => void
type TestNameLike = Global.TestNameLike;
1,778
(testName: TestNameLike, testFn: ConcurrentTestFn, timeout?: number): void
type TestNameLike = TestName | NameLike;
1,779
(testName: TestNameLike, testFn: ConcurrentTestFn, timeout?: number): void
type TestNameLike = Global.TestNameLike;
1,780
(testName: TestNameLike, testFn: ConcurrentTestFn, timeout?: number): void
type ConcurrentTestFn = () => TestReturnValuePromise;
1,781
(testName: TestNameLike, testFn: ConcurrentTestFn, timeout?: number): void
type ConcurrentTestFn = Global.ConcurrentTestFn;
1,782
(blockName: BlockNameLike, blockFn: BlockFn): void
type BlockNameLike = BlockName | NameLike;
1,783
(blockName: BlockNameLike, blockFn: BlockFn): void
type BlockNameLike = Global.BlockNameLike;
1,784
(blockName: BlockNameLike, blockFn: BlockFn): void
type BlockFn = () => void;
1,785
(blockName: BlockNameLike, blockFn: BlockFn): void
type BlockFn = Global.BlockFn;
1,786
(event: AsyncEvent, state: State): void | Promise<void>
type AsyncEvent = | { // first action to dispatch. Good time to initialize all settings name: 'setup'; testNamePattern?: string; runtimeGlobals: JestGlobals; parentProcess: Process; } | { name: 'include_test_location_in_result'; } | { name: 'hook_start'; hook: Hook; } | { name: 'hook_success'; describeBlock?: DescribeBlock; test?: TestEntry; hook: Hook; } | { name: 'hook_failure'; error: string | Exception; describeBlock?: DescribeBlock; test?: TestEntry; hook: Hook; } | { name: 'test_fn_start'; test: TestEntry; } | { name: 'test_fn_success'; test: TestEntry; } | { name: 'test_fn_failure'; error: Exception; test: TestEntry; } | { name: 'test_retry'; test: TestEntry; } | { // the `test` in this case is all hooks + it/test function, not just the // function passed to `it/test` name: 'test_start'; test: TestEntry; } | { name: 'test_skip'; test: TestEntry; } | { name: 'test_todo'; test: TestEntry; } | { // test failure is defined by presence of errors in `test.errors`, // `test_done` indicates that the test and all its hooks were run, // and nothing else will change it's state in the future. (except third // party extentions/plugins) name: 'test_done'; test: TestEntry; } | { name: 'run_describe_start'; describeBlock: DescribeBlock; } | { name: 'run_describe_finish'; describeBlock: DescribeBlock; } | { name: 'run_start'; } | { name: 'run_finish'; } | { // Action dispatched after everything is finished and we're about to wrap // things up and return test results to the parent process (caller). name: 'teardown'; };
1,787
(event: AsyncEvent, state: State): void | Promise<void>
type State = Circus.State;
1,788
(event: AsyncEvent, state: State): void | Promise<void>
type State = { interrupted: boolean; };
1,789
(event: AsyncEvent, state: State): void | Promise<void>
type State = { currentDescribeBlock: DescribeBlock; currentlyRunningTest?: TestEntry | null; // including when hooks are being executed expand?: boolean; // expand error messages hasFocusedTests: boolean; // that are defined using test.only hasStarted: boolean; // whether the rootDescribeBlock has started running // Store process error handlers. During the run we inject our own // handlers (so we could fail tests on unhandled errors) and later restore // the original ones. originalGlobalErrorHandlers?: GlobalErrorHandlers; parentProcess: Process | null; // process object from the outer scope rootDescribeBlock: DescribeBlock; testNamePattern?: RegExp | null; testTimeout: number; unhandledErrors: Array<Exception>; includeTestLocationInResult: boolean; maxConcurrency: number; };
1,790
(event: SyncEvent, state: State): void
type SyncEvent = | { asyncError: Error; mode: BlockMode; name: 'start_describe_definition'; blockName: BlockName; } | { mode: BlockMode; name: 'finish_describe_definition'; blockName: BlockName; } | { asyncError: Error; name: 'add_hook'; hookType: HookType; fn: HookFn; timeout: number | undefined; } | { asyncError: Error; name: 'add_test'; testName: TestName; fn: TestFn; mode?: TestMode; concurrent: boolean; timeout: number | undefined; failing: boolean; } | { // Any unhandled error that happened outside of test/hooks (unless it is // an `afterAll` hook) name: 'error'; error: Exception; };
1,791
(event: SyncEvent, state: State): void
type State = Circus.State;
1,792
(event: SyncEvent, state: State): void
type State = { interrupted: boolean; };
1,793
(event: SyncEvent, state: State): void
type State = { currentDescribeBlock: DescribeBlock; currentlyRunningTest?: TestEntry | null; // including when hooks are being executed expand?: boolean; // expand error messages hasFocusedTests: boolean; // that are defined using test.only hasStarted: boolean; // whether the rootDescribeBlock has started running // Store process error handlers. During the run we inject our own // handlers (so we could fail tests on unhandled errors) and later restore // the original ones. originalGlobalErrorHandlers?: GlobalErrorHandlers; parentProcess: Process | null; // process object from the outer scope rootDescribeBlock: DescribeBlock; testNamePattern?: RegExp | null; testTimeout: number; unhandledErrors: Array<Exception>; includeTestLocationInResult: boolean; maxConcurrency: number; };
1,794
(exception: Exception) => void
type Exception = any;
1,795
(exception: Exception, promise: Promise<unknown>) => void
type Exception = any;
1,796
createWorker(options: WorkerOptions): WorkerInterface
type WorkerOptions = { forkOptions: ForkOptions; resourceLimits: ResourceLimits; setupArgs: Array<unknown>; maxRetries: number; workerId: number; workerData?: unknown; workerPath: string; /** * After a job has executed the memory usage it should return to. * * @remarks * Note this is different from ResourceLimits in that it checks at idle, after * a job is complete. So you could have a resource limit of 500MB but an idle * limit of 50MB. The latter will only trigger if after a job has completed the * memory usage hasn't returned back down under 50MB. */ idleMemoryLimit?: number; /** * This mainly exists so the path can be changed during testing. * https://github.com/facebook/jest/issues/9543 */ childWorkerPath?: string; /** * This is useful for debugging individual tests allowing you to see * the raw output of the worker. */ silent?: boolean; /** * Used to immediately bind event handlers. */ on?: { [WorkerEvents.STATE_CHANGE]: | OnStateChangeHandler | ReadonlyArray<OnStateChangeHandler>; }; };
1,797
send( request: ChildMessage, onProcessStart: OnStart, onProcessEnd: OnEnd, onCustomMessage: OnCustomMessage, ): void
type OnStart = (worker: WorkerInterface) => void;
1,798
send( request: ChildMessage, onProcessStart: OnStart, onProcessEnd: OnEnd, onCustomMessage: OnCustomMessage, ): void
type OnCustomMessage = (message: Array<unknown> | unknown) => void;
1,799
send( request: ChildMessage, onProcessStart: OnStart, onProcessEnd: OnEnd, onCustomMessage: OnCustomMessage, ): void
type OnEnd = (err: Error | null, result: unknown) => void;