id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
1,500
(context: Spec) => void
class Spec { id: string; description: string; resultCallback: (result: SpecResult) => void; queueableFn: QueueableFn; beforeAndAfterFns: () => { befores: Array<QueueableFn>; afters: Array<QueueableFn>; }; userContext: () => unknown; onStart: (spec: Spec) => void; getSpecName: (spec: Spec) => string; queueRunnerFactory: typeof queueRunner; throwOnExpectationFailure: boolean; initError: Error; result: SpecResult; disabled?: boolean; currentRun?: ReturnType<typeof queueRunner>; markedTodo?: boolean; markedPending?: boolean; expand?: boolean; static pendingSpecExceptionMessage: string; static isPendingSpecException(e: Error) { return !!( e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 ); } constructor(attrs: Attributes) { this.resultCallback = attrs.resultCallback || function () {}; this.id = attrs.id; this.description = convertDescriptorToString(attrs.description); this.queueableFn = attrs.queueableFn; this.beforeAndAfterFns = attrs.beforeAndAfterFns || function () { return {befores: [], afters: []}; }; this.userContext = attrs.userContext || function () { return {}; }; this.onStart = attrs.onStart || function () {}; this.getSpecName = attrs.getSpecName || function () { return ''; }; this.queueRunnerFactory = attrs.queueRunnerFactory || function () {}; this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.initError = new Error(); this.initError.name = ''; // Without this line v8 stores references to all closures // in the stack in the Error object. This line stringifies the stack // property to allow garbage-collecting objects on the stack // https://crbug.com/v8/7142 // eslint-disable-next-line no-self-assign this.initError.stack = this.initError.stack; this.queueableFn.initError = this.initError; // @ts-expect-error: misses some fields added later this.result = { id: this.id, description: this.description, fullName: this.getFullName(), failedExpectations: [], passedExpectations: [], pendingReason: '', testPath: attrs.getTestPath(), }; } addExpectationResult( passed: boolean, data: ExpectationResultFactoryOptions, isError?: boolean, ) { const expectationResult = expectationResultFactory(data, this.initError); if (passed) { this.result.passedExpectations.push(expectationResult); } else { this.result.failedExpectations.push(expectationResult); if (this.throwOnExpectationFailure && !isError) { throw new ExpectationFailed(); } } } execute(onComplete?: () => void, enabled?: boolean) { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; this.onStart(this); if ( !this.isExecutable() || this.markedPending || this.markedTodo || enabled === false ) { complete(enabled); return; } const fns = this.beforeAndAfterFns(); const allFns = fns.befores.concat(this.queueableFn).concat(fns.afters); this.currentRun = this.queueRunnerFactory({ queueableFns: allFns, onException() { // @ts-expect-error: wrong context self.onException.apply(self, arguments); }, userContext: this.userContext(), setTimeout, clearTimeout, fail: () => {}, }); this.currentRun.then(() => complete(true)); function complete(enabledAgain?: boolean) { self.result.status = self.status(enabledAgain); self.resultCallback(self.result); if (onComplete) { onComplete(); } } } cancel() { if (this.currentRun) { this.currentRun.cancel(); } } onException(error: ExpectationFailed | AssertionErrorWithStack) { if (Spec.isPendingSpecException(error)) { this.pend(extractCustomPendingMessage(error)); return; } if (error instanceof ExpectationFailed) { return; } this.addExpectationResult( false, { matcherName: '', passed: false, expected: '', actual: '', error: this.isAssertionError(error) ? assertionErrorMessage(error, {expand: this.expand}) : error, }, true, ); } disable() { this.disabled = true; } pend(message?: string) { this.markedPending = true; if (message) { this.result.pendingReason = message; } } todo() { this.markedTodo = true; } getResult() { this.result.status = this.status(); return this.result; } status(enabled?: boolean) { if (this.disabled || enabled === false) { return 'disabled'; } if (this.markedTodo) { return 'todo'; } if (this.markedPending) { return 'pending'; } if (this.result.failedExpectations.length > 0) { return 'failed'; } else { return 'passed'; } } isExecutable() { return !this.disabled; } getFullName() { return this.getSpecName(this); } isAssertionError(error: Error) { return ( error instanceof AssertionError || (error && error.name === AssertionError.name) ); } }
1,501
(spec: Spec) => string
class Spec extends realSpec { constructor(attr: Attributes) { const resultCallback = attr.resultCallback; attr.resultCallback = function (result: SpecResult) { addSuppressedErrors(result); addAssertionErrors(result); resultCallback.call(attr, result); }; const onStart = attr.onStart; attr.onStart = (context: JasmineSpec) => { jestExpect.setState({currentTestName: context.getFullName()}); onStart && onStart.call(attr, context); }; super(attr); } }
1,502
(spec: Spec) => string
class Spec { id: string; description: string; resultCallback: (result: SpecResult) => void; queueableFn: QueueableFn; beforeAndAfterFns: () => { befores: Array<QueueableFn>; afters: Array<QueueableFn>; }; userContext: () => unknown; onStart: (spec: Spec) => void; getSpecName: (spec: Spec) => string; queueRunnerFactory: typeof queueRunner; throwOnExpectationFailure: boolean; initError: Error; result: SpecResult; disabled?: boolean; currentRun?: ReturnType<typeof queueRunner>; markedTodo?: boolean; markedPending?: boolean; expand?: boolean; static pendingSpecExceptionMessage: string; static isPendingSpecException(e: Error) { return !!( e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 ); } constructor(attrs: Attributes) { this.resultCallback = attrs.resultCallback || function () {}; this.id = attrs.id; this.description = convertDescriptorToString(attrs.description); this.queueableFn = attrs.queueableFn; this.beforeAndAfterFns = attrs.beforeAndAfterFns || function () { return {befores: [], afters: []}; }; this.userContext = attrs.userContext || function () { return {}; }; this.onStart = attrs.onStart || function () {}; this.getSpecName = attrs.getSpecName || function () { return ''; }; this.queueRunnerFactory = attrs.queueRunnerFactory || function () {}; this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.initError = new Error(); this.initError.name = ''; // Without this line v8 stores references to all closures // in the stack in the Error object. This line stringifies the stack // property to allow garbage-collecting objects on the stack // https://crbug.com/v8/7142 // eslint-disable-next-line no-self-assign this.initError.stack = this.initError.stack; this.queueableFn.initError = this.initError; // @ts-expect-error: misses some fields added later this.result = { id: this.id, description: this.description, fullName: this.getFullName(), failedExpectations: [], passedExpectations: [], pendingReason: '', testPath: attrs.getTestPath(), }; } addExpectationResult( passed: boolean, data: ExpectationResultFactoryOptions, isError?: boolean, ) { const expectationResult = expectationResultFactory(data, this.initError); if (passed) { this.result.passedExpectations.push(expectationResult); } else { this.result.failedExpectations.push(expectationResult); if (this.throwOnExpectationFailure && !isError) { throw new ExpectationFailed(); } } } execute(onComplete?: () => void, enabled?: boolean) { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; this.onStart(this); if ( !this.isExecutable() || this.markedPending || this.markedTodo || enabled === false ) { complete(enabled); return; } const fns = this.beforeAndAfterFns(); const allFns = fns.befores.concat(this.queueableFn).concat(fns.afters); this.currentRun = this.queueRunnerFactory({ queueableFns: allFns, onException() { // @ts-expect-error: wrong context self.onException.apply(self, arguments); }, userContext: this.userContext(), setTimeout, clearTimeout, fail: () => {}, }); this.currentRun.then(() => complete(true)); function complete(enabledAgain?: boolean) { self.result.status = self.status(enabledAgain); self.resultCallback(self.result); if (onComplete) { onComplete(); } } } cancel() { if (this.currentRun) { this.currentRun.cancel(); } } onException(error: ExpectationFailed | AssertionErrorWithStack) { if (Spec.isPendingSpecException(error)) { this.pend(extractCustomPendingMessage(error)); return; } if (error instanceof ExpectationFailed) { return; } this.addExpectationResult( false, { matcherName: '', passed: false, expected: '', actual: '', error: this.isAssertionError(error) ? assertionErrorMessage(error, {expand: this.expand}) : error, }, true, ); } disable() { this.disabled = true; } pend(message?: string) { this.markedPending = true; if (message) { this.result.pendingReason = message; } } todo() { this.markedTodo = true; } getResult() { this.result.status = this.status(); return this.result; } status(enabled?: boolean) { if (this.disabled || enabled === false) { return 'disabled'; } if (this.markedTodo) { return 'todo'; } if (this.markedPending) { return 'pending'; } if (this.result.failedExpectations.length > 0) { return 'failed'; } else { return 'passed'; } } isExecutable() { return !this.disabled; } getFullName() { return this.getSpecName(this); } isAssertionError(error: Error) { return ( error instanceof AssertionError || (error && error.name === AssertionError.name) ); } }
1,503
(spec: Spec) => void
class Spec extends realSpec { constructor(attr: Attributes) { const resultCallback = attr.resultCallback; attr.resultCallback = function (result: SpecResult) { addSuppressedErrors(result); addAssertionErrors(result); resultCallback.call(attr, result); }; const onStart = attr.onStart; attr.onStart = (context: JasmineSpec) => { jestExpect.setState({currentTestName: context.getFullName()}); onStart && onStart.call(attr, context); }; super(attr); } }
1,504
(spec: Spec) => void
class Spec { id: string; description: string; resultCallback: (result: SpecResult) => void; queueableFn: QueueableFn; beforeAndAfterFns: () => { befores: Array<QueueableFn>; afters: Array<QueueableFn>; }; userContext: () => unknown; onStart: (spec: Spec) => void; getSpecName: (spec: Spec) => string; queueRunnerFactory: typeof queueRunner; throwOnExpectationFailure: boolean; initError: Error; result: SpecResult; disabled?: boolean; currentRun?: ReturnType<typeof queueRunner>; markedTodo?: boolean; markedPending?: boolean; expand?: boolean; static pendingSpecExceptionMessage: string; static isPendingSpecException(e: Error) { return !!( e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 ); } constructor(attrs: Attributes) { this.resultCallback = attrs.resultCallback || function () {}; this.id = attrs.id; this.description = convertDescriptorToString(attrs.description); this.queueableFn = attrs.queueableFn; this.beforeAndAfterFns = attrs.beforeAndAfterFns || function () { return {befores: [], afters: []}; }; this.userContext = attrs.userContext || function () { return {}; }; this.onStart = attrs.onStart || function () {}; this.getSpecName = attrs.getSpecName || function () { return ''; }; this.queueRunnerFactory = attrs.queueRunnerFactory || function () {}; this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.initError = new Error(); this.initError.name = ''; // Without this line v8 stores references to all closures // in the stack in the Error object. This line stringifies the stack // property to allow garbage-collecting objects on the stack // https://crbug.com/v8/7142 // eslint-disable-next-line no-self-assign this.initError.stack = this.initError.stack; this.queueableFn.initError = this.initError; // @ts-expect-error: misses some fields added later this.result = { id: this.id, description: this.description, fullName: this.getFullName(), failedExpectations: [], passedExpectations: [], pendingReason: '', testPath: attrs.getTestPath(), }; } addExpectationResult( passed: boolean, data: ExpectationResultFactoryOptions, isError?: boolean, ) { const expectationResult = expectationResultFactory(data, this.initError); if (passed) { this.result.passedExpectations.push(expectationResult); } else { this.result.failedExpectations.push(expectationResult); if (this.throwOnExpectationFailure && !isError) { throw new ExpectationFailed(); } } } execute(onComplete?: () => void, enabled?: boolean) { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; this.onStart(this); if ( !this.isExecutable() || this.markedPending || this.markedTodo || enabled === false ) { complete(enabled); return; } const fns = this.beforeAndAfterFns(); const allFns = fns.befores.concat(this.queueableFn).concat(fns.afters); this.currentRun = this.queueRunnerFactory({ queueableFns: allFns, onException() { // @ts-expect-error: wrong context self.onException.apply(self, arguments); }, userContext: this.userContext(), setTimeout, clearTimeout, fail: () => {}, }); this.currentRun.then(() => complete(true)); function complete(enabledAgain?: boolean) { self.result.status = self.status(enabledAgain); self.resultCallback(self.result); if (onComplete) { onComplete(); } } } cancel() { if (this.currentRun) { this.currentRun.cancel(); } } onException(error: ExpectationFailed | AssertionErrorWithStack) { if (Spec.isPendingSpecException(error)) { this.pend(extractCustomPendingMessage(error)); return; } if (error instanceof ExpectationFailed) { return; } this.addExpectationResult( false, { matcherName: '', passed: false, expected: '', actual: '', error: this.isAssertionError(error) ? assertionErrorMessage(error, {expand: this.expand}) : error, }, true, ); } disable() { this.disabled = true; } pend(message?: string) { this.markedPending = true; if (message) { this.result.pendingReason = message; } } todo() { this.markedTodo = true; } getResult() { this.result.status = this.status(); return this.result; } status(enabled?: boolean) { if (this.disabled || enabled === false) { return 'disabled'; } if (this.markedTodo) { return 'todo'; } if (this.markedPending) { return 'pending'; } if (this.result.failedExpectations.length > 0) { return 'failed'; } else { return 'passed'; } } isExecutable() { return !this.disabled; } getFullName() { return this.getSpecName(this); } isAssertionError(error: Error) { return ( error instanceof AssertionError || (error && error.name === AssertionError.name) ); } }
1,505
constructor(attrs: Attributes) { this.resultCallback = attrs.resultCallback || function () {}; this.id = attrs.id; this.description = convertDescriptorToString(attrs.description); this.queueableFn = attrs.queueableFn; this.beforeAndAfterFns = attrs.beforeAndAfterFns || function () { return {befores: [], afters: []}; }; this.userContext = attrs.userContext || function () { return {}; }; this.onStart = attrs.onStart || function () {}; this.getSpecName = attrs.getSpecName || function () { return ''; }; this.queueRunnerFactory = attrs.queueRunnerFactory || function () {}; this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.initError = new Error(); this.initError.name = ''; // Without this line v8 stores references to all closures // in the stack in the Error object. This line stringifies the stack // property to allow garbage-collecting objects on the stack // https://crbug.com/v8/7142 // eslint-disable-next-line no-self-assign this.initError.stack = this.initError.stack; this.queueableFn.initError = this.initError; // @ts-expect-error: misses some fields added later this.result = { id: this.id, description: this.description, fullName: this.getFullName(), failedExpectations: [], passedExpectations: [], pendingReason: '', testPath: attrs.getTestPath(), }; }
type Attributes = { id: string; parentSuite?: Suite; description: Circus.TestNameLike; throwOnExpectationFailure?: boolean; getTestPath: () => string; };
1,506
constructor(attrs: Attributes) { this.resultCallback = attrs.resultCallback || function () {}; this.id = attrs.id; this.description = convertDescriptorToString(attrs.description); this.queueableFn = attrs.queueableFn; this.beforeAndAfterFns = attrs.beforeAndAfterFns || function () { return {befores: [], afters: []}; }; this.userContext = attrs.userContext || function () { return {}; }; this.onStart = attrs.onStart || function () {}; this.getSpecName = attrs.getSpecName || function () { return ''; }; this.queueRunnerFactory = attrs.queueRunnerFactory || function () {}; this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.initError = new Error(); this.initError.name = ''; // Without this line v8 stores references to all closures // in the stack in the Error object. This line stringifies the stack // property to allow garbage-collecting objects on the stack // https://crbug.com/v8/7142 // eslint-disable-next-line no-self-assign this.initError.stack = this.initError.stack; this.queueableFn.initError = this.initError; // @ts-expect-error: misses some fields added later this.result = { id: this.id, description: this.description, fullName: this.getFullName(), failedExpectations: [], passedExpectations: [], pendingReason: '', testPath: attrs.getTestPath(), }; }
type Attributes = { id: string; resultCallback: (result: Spec['result']) => void; description: Circus.TestNameLike; throwOnExpectationFailure: unknown; getTestPath: () => string; queueableFn: QueueableFn; beforeAndAfterFns: () => { befores: Array<QueueableFn>; afters: Array<QueueableFn>; }; userContext: () => unknown; onStart: (context: Spec) => void; getSpecName: (spec: Spec) => string; queueRunnerFactory: typeof queueRunner; };
1,507
function validateAfterAllExceptions({failedExpectations}: RunDetails) { if (failedExpectations && failedExpectations.length > 0) { throw failedExpectations[0]; } }
type RunDetails = { totalSpecsDefined?: number; failedExpectations?: SuiteResult['failedExpectations']; };
1,508
function (result: SuiteResult) { suites_hash[result.id] = result; }
type SuiteResult = { id: string; description: string; fullName: string; failedExpectations: Array<ReturnType<typeof expectationResultFactory>>; testPath: string; status?: string; };
1,509
function (result: SuiteResult) { storeSuite(result); }
type SuiteResult = { id: string; description: string; fullName: string; failedExpectations: Array<ReturnType<typeof expectationResultFactory>>; testPath: string; status?: string; };
1,510
function storeSuite(result: SuiteResult) { suites.push(result); suites_hash[result.id] = result; }
type SuiteResult = { id: string; description: string; fullName: string; failedExpectations: Array<ReturnType<typeof expectationResultFactory>>; testPath: string; status?: string; };
1,511
function assertionErrorMessage( error: AssertionErrorWithStack, options: DiffOptions, ) { const {expected, actual, generatedMessage, message, operator, stack} = error; const diffString = diff(expected, actual, options); const hasCustomMessage = !generatedMessage; const operatorName = getOperatorName(operator, stack); const trimmedStack = stack .replace(message, '') .replace(/AssertionError(.*)/g, ''); if (operatorName === 'doesNotThrow') { return ( // eslint-disable-next-line prefer-template buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function not to throw an error.\n') + chalk.reset('Instead, it threw:\n') + ` ${printReceived(actual)}` + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } if (operatorName === 'throws') { if (error.generatedMessage) { return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset(error.message) + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function to throw an error.\n') + chalk.reset("But it didn't throw anything.") + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } if (operatorName === 'fail') { return ( buildHintString(assertMatcherHint(operator, operatorName, expected)) + chalk.reset(hasCustomMessage ? `Message:\n ${message}` : '') + trimmedStack ); } return ( // eslint-disable-next-line prefer-template buildHintString(assertMatcherHint(operator, operatorName, expected)) + chalk.reset(`Expected value ${operatorMessage(operator)}`) + ` ${printExpected(expected)}\n` + chalk.reset('Received:\n') + ` ${printReceived(actual)}` + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + (diffString ? `\n\nDifference:\n\n${diffString}` : '') + trimmedStack ); }
type DiffOptions = { aAnnotation?: string; aColor?: DiffOptionsColor; aIndicator?: string; bAnnotation?: string; bColor?: DiffOptionsColor; bIndicator?: string; changeColor?: DiffOptionsColor; changeLineTrailingSpaceColor?: DiffOptionsColor; commonColor?: DiffOptionsColor; commonIndicator?: string; commonLineTrailingSpaceColor?: DiffOptionsColor; contextLines?: number; emptyFirstOrLastLinePlaceholder?: string; expand?: boolean; includeChangeCounts?: boolean; omitAnnotationLines?: boolean; patchColor?: DiffOptionsColor; compareKeys?: CompareKeys; };
1,512
function assertionErrorMessage( error: AssertionErrorWithStack, options: DiffOptions, ) { const {expected, actual, generatedMessage, message, operator, stack} = error; const diffString = diff(expected, actual, options); const hasCustomMessage = !generatedMessage; const operatorName = getOperatorName(operator, stack); const trimmedStack = stack .replace(message, '') .replace(/AssertionError(.*)/g, ''); if (operatorName === 'doesNotThrow') { return ( // eslint-disable-next-line prefer-template buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function not to throw an error.\n') + chalk.reset('Instead, it threw:\n') + ` ${printReceived(actual)}` + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } if (operatorName === 'throws') { if (error.generatedMessage) { return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset(error.message) + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function to throw an error.\n') + chalk.reset("But it didn't throw anything.") + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } if (operatorName === 'fail') { return ( buildHintString(assertMatcherHint(operator, operatorName, expected)) + chalk.reset(hasCustomMessage ? `Message:\n ${message}` : '') + trimmedStack ); } return ( // eslint-disable-next-line prefer-template buildHintString(assertMatcherHint(operator, operatorName, expected)) + chalk.reset(`Expected value ${operatorMessage(operator)}`) + ` ${printExpected(expected)}\n` + chalk.reset('Received:\n') + ` ${printReceived(actual)}` + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + (diffString ? `\n\nDifference:\n\n${diffString}` : '') + trimmedStack ); }
type DiffOptions = ImportDiffOptions;
1,513
function assertionErrorMessage( error: AssertionErrorWithStack, options: DiffOptions, ) { const {expected, actual, generatedMessage, message, operator, stack} = error; const diffString = diff(expected, actual, options); const hasCustomMessage = !generatedMessage; const operatorName = getOperatorName(operator, stack); const trimmedStack = stack .replace(message, '') .replace(/AssertionError(.*)/g, ''); if (operatorName === 'doesNotThrow') { return ( // eslint-disable-next-line prefer-template buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function not to throw an error.\n') + chalk.reset('Instead, it threw:\n') + ` ${printReceived(actual)}` + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } if (operatorName === 'throws') { if (error.generatedMessage) { return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset(error.message) + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function to throw an error.\n') + chalk.reset("But it didn't throw anything.") + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } if (operatorName === 'fail') { return ( buildHintString(assertMatcherHint(operator, operatorName, expected)) + chalk.reset(hasCustomMessage ? `Message:\n ${message}` : '') + trimmedStack ); } return ( // eslint-disable-next-line prefer-template buildHintString(assertMatcherHint(operator, operatorName, expected)) + chalk.reset(`Expected value ${operatorMessage(operator)}`) + ` ${printExpected(expected)}\n` + chalk.reset('Received:\n') + ` ${printReceived(actual)}` + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + (diffString ? `\n\nDifference:\n\n${diffString}` : '') + trimmedStack ); }
interface AssertionErrorWithStack extends AssertionError { stack: string; }
1,514
function assertionErrorMessage( error: AssertionErrorWithStack, options: DiffOptions, ) { const {expected, actual, generatedMessage, message, operator, stack} = error; const diffString = diff(expected, actual, options); const hasCustomMessage = !generatedMessage; const operatorName = getOperatorName(operator, stack); const trimmedStack = stack .replace(message, '') .replace(/AssertionError(.*)/g, ''); if (operatorName === 'doesNotThrow') { return ( // eslint-disable-next-line prefer-template buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function not to throw an error.\n') + chalk.reset('Instead, it threw:\n') + ` ${printReceived(actual)}` + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } if (operatorName === 'throws') { if (error.generatedMessage) { return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset(error.message) + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function to throw an error.\n') + chalk.reset("But it didn't throw anything.") + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack ); } if (operatorName === 'fail') { return ( buildHintString(assertMatcherHint(operator, operatorName, expected)) + chalk.reset(hasCustomMessage ? `Message:\n ${message}` : '') + trimmedStack ); } return ( // eslint-disable-next-line prefer-template buildHintString(assertMatcherHint(operator, operatorName, expected)) + chalk.reset(`Expected value ${operatorMessage(operator)}`) + ` ${printExpected(expected)}\n` + chalk.reset('Received:\n') + ` ${printReceived(actual)}` + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + (diffString ? `\n\nDifference:\n\n${diffString}` : '') + trimmedStack ); }
interface AssertionErrorWithStack extends AssertionError { stack: string; }
1,515
(globals: RuntimeGlobals) => void
interface RuntimeGlobals extends Global.TestFrameworkGlobals { expect: JestExpect; }
1,516
(snapshotState: SnapshotState) => (event: Circus.Event) => { switch (event.name) { case 'test_retry': { // Clear any snapshot data that occurred in previous test run snapshotState.clear(); } } }
class SnapshotState { private _counters: Map<string, number>; private _dirty: boolean; // @ts-expect-error - seemingly unused? private _index: number; private readonly _updateSnapshot: Config.SnapshotUpdateState; private _snapshotData: SnapshotData; private readonly _initialData: SnapshotData; private readonly _snapshotPath: string; private _inlineSnapshots: Array<InlineSnapshot>; private readonly _uncheckedKeys: Set<string>; private readonly _prettierPath: string | null; private readonly _rootDir: string; readonly snapshotFormat: SnapshotFormat; added: number; expand: boolean; matched: number; unmatched: number; updated: number; constructor(snapshotPath: string, options: SnapshotStateOptions) { this._snapshotPath = snapshotPath; const {data, dirty} = getSnapshotData( this._snapshotPath, options.updateSnapshot, ); this._initialData = data; this._snapshotData = data; this._dirty = dirty; this._prettierPath = options.prettierPath ?? null; this._inlineSnapshots = []; this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); this._counters = new Map(); this._index = 0; this.expand = options.expand || false; this.added = 0; this.matched = 0; this.unmatched = 0; this._updateSnapshot = options.updateSnapshot; this.updated = 0; this.snapshotFormat = options.snapshotFormat; this._rootDir = options.rootDir; } markSnapshotsAsCheckedForTest(testName: string): void { this._uncheckedKeys.forEach(uncheckedKey => { if (keyToTestName(uncheckedKey) === testName) { this._uncheckedKeys.delete(uncheckedKey); } }); } private _addSnapshot( key: string, receivedSerialized: string, options: {isInline: boolean; error?: Error}, ): void { this._dirty = true; if (options.isInline) { const error = options.error || new Error(); const lines = getStackTraceLines( removeLinesBeforeExternalMatcherTrap(error.stack || ''), ); const frame = getTopFrame(lines); if (!frame) { throw new Error( "Jest: Couldn't infer stack frame for inline snapshot.", ); } this._inlineSnapshots.push({ frame, snapshot: receivedSerialized, }); } else { this._snapshotData[key] = receivedSerialized; } } clear(): void { this._snapshotData = this._initialData; this._inlineSnapshots = []; this._counters = new Map(); this._index = 0; this.added = 0; this.matched = 0; this.unmatched = 0; this.updated = 0; } save(): SaveStatus { const hasExternalSnapshots = Object.keys(this._snapshotData).length; const hasInlineSnapshots = this._inlineSnapshots.length; const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots; const status: SaveStatus = { deleted: false, saved: false, }; if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) { if (hasExternalSnapshots) { saveSnapshotFile(this._snapshotData, this._snapshotPath); } if (hasInlineSnapshots) { saveInlineSnapshots( this._inlineSnapshots, this._rootDir, this._prettierPath, ); } status.saved = true; } else if (!hasExternalSnapshots && fs.existsSync(this._snapshotPath)) { if (this._updateSnapshot === 'all') { fs.unlinkSync(this._snapshotPath); } status.deleted = true; } return status; } getUncheckedCount(): number { return this._uncheckedKeys.size || 0; } getUncheckedKeys(): Array<string> { return Array.from(this._uncheckedKeys); } removeUncheckedKeys(): void { if (this._updateSnapshot === 'all' && this._uncheckedKeys.size) { this._dirty = true; this._uncheckedKeys.forEach(key => delete this._snapshotData[key]); this._uncheckedKeys.clear(); } } match({ testName, received, key, inlineSnapshot, isInline, error, }: SnapshotMatchOptions): SnapshotReturnOptions { this._counters.set(testName, (this._counters.get(testName) || 0) + 1); const count = Number(this._counters.get(testName)); if (!key) { key = testNameToKey(testName, count); } // Do not mark the snapshot as "checked" if the snapshot is inline and // there's an external snapshot. This way the external snapshot can be // removed with `--updateSnapshot`. if (!(isInline && this._snapshotData[key] !== undefined)) { this._uncheckedKeys.delete(key); } const receivedSerialized = addExtraLineBreaks( serialize(received, undefined, this.snapshotFormat), ); const expected = isInline ? inlineSnapshot : this._snapshotData[key]; const pass = expected === receivedSerialized; const hasSnapshot = expected !== undefined; const snapshotIsPersisted = isInline || fs.existsSync(this._snapshotPath); if (pass && !isInline) { // Executing a snapshot file as JavaScript and writing the strings back // when other snapshots have changed loses the proper escaping for some // characters. Since we check every snapshot in every test, use the newly // generated formatted string. // Note that this is only relevant when a snapshot is added and the dirty // flag is set. this._snapshotData[key] = receivedSerialized; } // These are the conditions on when to write snapshots: // * There's no snapshot file in a non-CI environment. // * There is a snapshot file and we decided to update the snapshot. // * There is a snapshot file, but it doesn't have this snaphsot. // These are the conditions on when not to write snapshots: // * The update flag is set to 'none'. // * There's no snapshot file or a file without this snapshot on a CI environment. if ( (hasSnapshot && this._updateSnapshot === 'all') || ((!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === 'new' || this._updateSnapshot === 'all')) ) { if (this._updateSnapshot === 'all') { if (!pass) { if (hasSnapshot) { this.updated++; } else { this.added++; } this._addSnapshot(key, receivedSerialized, {error, isInline}); } else { this.matched++; } } else { this._addSnapshot(key, receivedSerialized, {error, isInline}); this.added++; } return { actual: '', count, expected: '', key, pass: true, }; } else { if (!pass) { this.unmatched++; return { actual: removeExtraLineBreaks(receivedSerialized), count, expected: expected !== undefined ? removeExtraLineBreaks(expected) : undefined, key, pass: false, }; } else { this.matched++; return { actual: '', count, expected: '', key, pass: true, }; } } } fail(testName: string, _received: unknown, key?: string): string { this._counters.set(testName, (this._counters.get(testName) || 0) + 1); const count = Number(this._counters.get(testName)); if (!key) { key = testNameToKey(testName, count); } this._uncheckedKeys.delete(key); this.unmatched++; return key; } }
1,517
( results: TestResult, snapshotState: SnapshotState, ) => { results.testResults.forEach(({fullName, status}) => { 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(); if (uncheckedCount) { snapshotState.removeUncheckedKeys(); } const status = snapshotState.save(); results.snapshot.fileDeleted = status.deleted; results.snapshot.added = snapshotState.added; results.snapshot.matched = snapshotState.matched; results.snapshot.unmatched = snapshotState.unmatched; results.snapshot.updated = snapshotState.updated; results.snapshot.unchecked = !status.deleted ? uncheckedCount : 0; // Copy the array to prevent memory leaks results.snapshot.uncheckedKeys = Array.from(uncheckedKeys); }
class SnapshotState { private _counters: Map<string, number>; private _dirty: boolean; // @ts-expect-error - seemingly unused? private _index: number; private readonly _updateSnapshot: Config.SnapshotUpdateState; private _snapshotData: SnapshotData; private readonly _initialData: SnapshotData; private readonly _snapshotPath: string; private _inlineSnapshots: Array<InlineSnapshot>; private readonly _uncheckedKeys: Set<string>; private readonly _prettierPath: string | null; private readonly _rootDir: string; readonly snapshotFormat: SnapshotFormat; added: number; expand: boolean; matched: number; unmatched: number; updated: number; constructor(snapshotPath: string, options: SnapshotStateOptions) { this._snapshotPath = snapshotPath; const {data, dirty} = getSnapshotData( this._snapshotPath, options.updateSnapshot, ); this._initialData = data; this._snapshotData = data; this._dirty = dirty; this._prettierPath = options.prettierPath ?? null; this._inlineSnapshots = []; this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); this._counters = new Map(); this._index = 0; this.expand = options.expand || false; this.added = 0; this.matched = 0; this.unmatched = 0; this._updateSnapshot = options.updateSnapshot; this.updated = 0; this.snapshotFormat = options.snapshotFormat; this._rootDir = options.rootDir; } markSnapshotsAsCheckedForTest(testName: string): void { this._uncheckedKeys.forEach(uncheckedKey => { if (keyToTestName(uncheckedKey) === testName) { this._uncheckedKeys.delete(uncheckedKey); } }); } private _addSnapshot( key: string, receivedSerialized: string, options: {isInline: boolean; error?: Error}, ): void { this._dirty = true; if (options.isInline) { const error = options.error || new Error(); const lines = getStackTraceLines( removeLinesBeforeExternalMatcherTrap(error.stack || ''), ); const frame = getTopFrame(lines); if (!frame) { throw new Error( "Jest: Couldn't infer stack frame for inline snapshot.", ); } this._inlineSnapshots.push({ frame, snapshot: receivedSerialized, }); } else { this._snapshotData[key] = receivedSerialized; } } clear(): void { this._snapshotData = this._initialData; this._inlineSnapshots = []; this._counters = new Map(); this._index = 0; this.added = 0; this.matched = 0; this.unmatched = 0; this.updated = 0; } save(): SaveStatus { const hasExternalSnapshots = Object.keys(this._snapshotData).length; const hasInlineSnapshots = this._inlineSnapshots.length; const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots; const status: SaveStatus = { deleted: false, saved: false, }; if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) { if (hasExternalSnapshots) { saveSnapshotFile(this._snapshotData, this._snapshotPath); } if (hasInlineSnapshots) { saveInlineSnapshots( this._inlineSnapshots, this._rootDir, this._prettierPath, ); } status.saved = true; } else if (!hasExternalSnapshots && fs.existsSync(this._snapshotPath)) { if (this._updateSnapshot === 'all') { fs.unlinkSync(this._snapshotPath); } status.deleted = true; } return status; } getUncheckedCount(): number { return this._uncheckedKeys.size || 0; } getUncheckedKeys(): Array<string> { return Array.from(this._uncheckedKeys); } removeUncheckedKeys(): void { if (this._updateSnapshot === 'all' && this._uncheckedKeys.size) { this._dirty = true; this._uncheckedKeys.forEach(key => delete this._snapshotData[key]); this._uncheckedKeys.clear(); } } match({ testName, received, key, inlineSnapshot, isInline, error, }: SnapshotMatchOptions): SnapshotReturnOptions { this._counters.set(testName, (this._counters.get(testName) || 0) + 1); const count = Number(this._counters.get(testName)); if (!key) { key = testNameToKey(testName, count); } // Do not mark the snapshot as "checked" if the snapshot is inline and // there's an external snapshot. This way the external snapshot can be // removed with `--updateSnapshot`. if (!(isInline && this._snapshotData[key] !== undefined)) { this._uncheckedKeys.delete(key); } const receivedSerialized = addExtraLineBreaks( serialize(received, undefined, this.snapshotFormat), ); const expected = isInline ? inlineSnapshot : this._snapshotData[key]; const pass = expected === receivedSerialized; const hasSnapshot = expected !== undefined; const snapshotIsPersisted = isInline || fs.existsSync(this._snapshotPath); if (pass && !isInline) { // Executing a snapshot file as JavaScript and writing the strings back // when other snapshots have changed loses the proper escaping for some // characters. Since we check every snapshot in every test, use the newly // generated formatted string. // Note that this is only relevant when a snapshot is added and the dirty // flag is set. this._snapshotData[key] = receivedSerialized; } // These are the conditions on when to write snapshots: // * There's no snapshot file in a non-CI environment. // * There is a snapshot file and we decided to update the snapshot. // * There is a snapshot file, but it doesn't have this snaphsot. // These are the conditions on when not to write snapshots: // * The update flag is set to 'none'. // * There's no snapshot file or a file without this snapshot on a CI environment. if ( (hasSnapshot && this._updateSnapshot === 'all') || ((!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === 'new' || this._updateSnapshot === 'all')) ) { if (this._updateSnapshot === 'all') { if (!pass) { if (hasSnapshot) { this.updated++; } else { this.added++; } this._addSnapshot(key, receivedSerialized, {error, isInline}); } else { this.matched++; } } else { this._addSnapshot(key, receivedSerialized, {error, isInline}); this.added++; } return { actual: '', count, expected: '', key, pass: true, }; } else { if (!pass) { this.unmatched++; return { actual: removeExtraLineBreaks(receivedSerialized), count, expected: expected !== undefined ? removeExtraLineBreaks(expected) : undefined, key, pass: false, }; } else { this.matched++; return { actual: '', count, expected: '', key, pass: true, }; } } } fail(testName: string, _received: unknown, key?: string): string { this._counters.set(testName, (this._counters.get(testName) || 0) + 1); const count = Number(this._counters.get(testName)); if (!key) { key = testNameToKey(testName, count); } this._uncheckedKeys.delete(key); this.unmatched++; return key; } }
1,518
( results: TestResult, snapshotState: SnapshotState, ) => { results.testResults.forEach(({fullName, status}) => { 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(); if (uncheckedCount) { snapshotState.removeUncheckedKeys(); } const status = snapshotState.save(); results.snapshot.fileDeleted = status.deleted; results.snapshot.added = snapshotState.added; results.snapshot.matched = snapshotState.matched; results.snapshot.unmatched = snapshotState.unmatched; results.snapshot.updated = snapshotState.updated; results.snapshot.unchecked = !status.deleted ? uncheckedCount : 0; // Copy the array to prevent memory leaks results.snapshot.uncheckedKeys = Array.from(uncheckedKeys); }
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,519
( results: TestResult, snapshotState: SnapshotState, ) => { results.testResults.forEach(({fullName, status}) => { 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(); if (uncheckedCount) { snapshotState.removeUncheckedKeys(); } const status = snapshotState.save(); results.snapshot.fileDeleted = status.deleted; results.snapshot.added = snapshotState.added; results.snapshot.matched = snapshotState.matched; results.snapshot.unmatched = snapshotState.unmatched; results.snapshot.updated = snapshotState.updated; results.snapshot.unchecked = !status.deleted ? uncheckedCount : 0; // Copy the array to prevent memory leaks results.snapshot.uncheckedKeys = Array.from(uncheckedKeys); }
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,520
(fs: JestHookExposedFS) => void
type JestHookExposedFS = { projects: Array<{ config: Config.ProjectConfig; testPaths: Array<string>; }>; };
1,521
( testSuiteInfo: TestSuiteInfo, ) => Promise<boolean>
type TestSuiteInfo = { config: Config.ProjectConfig; duration?: number; testPath: string; };
1,522
(results: AggregatedResult) => void
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,523
(fn: FileChange) => void
type FileChange = (fs: JestHookExposedFS) => void;
1,524
(fn: TestRunComplete) => void
type TestRunComplete = (results: AggregatedResult) => void;
1,525
(fn: ShouldRunTestSuite) => void
type ShouldRunTestSuite = ( testSuiteInfo: TestSuiteInfo, ) => Promise<boolean>;
1,526
( testSuiteInfo: TestSuiteInfo, ) => Promise<boolean> | boolean
type TestSuiteInfo = { config: Config.ProjectConfig; duration?: number; testPath: string; };
1,527
(config?: AllowedConfigOptions) => void
type AllowedConfigOptions = Partial< Pick< Config.GlobalConfig, | 'bail' | 'changedSince' | 'collectCoverage' | 'collectCoverageFrom' | 'coverageDirectory' | 'coverageReporters' | 'findRelatedTests' | 'nonFlagArgs' | 'notify' | 'notifyMode' | 'onlyFailures' | 'reporters' | 'testNamePattern' | 'testPathPattern' | 'updateSnapshot' | 'verbose' > & {mode: 'watch' | 'watchAll'} >;
1,528
(hooks: JestHookSubscriber) => void
type JestHookSubscriber = { onFileChange: (fn: FileChange) => void; onTestRunComplete: (fn: TestRunComplete) => void; shouldRunTestSuite: (fn: ShouldRunTestSuite) => void; };
1,529
isUsed(hook: AvailableHooks): boolean { return this._listeners[hook]?.length > 0; }
type AvailableHooks = | 'onFileChange' | 'onTestRunComplete' | 'shouldRunTestSuite';
1,530
apply(_hooks: JestHookSubscriber): void {}
type JestHookSubscriber = { onFileChange: (fn: FileChange) => void; onTestRunComplete: (fn: TestRunComplete) => void; shouldRunTestSuite: (fn: ShouldRunTestSuite) => void; };
1,531
async setState(state: State): Promise<void> { Object.assign(this.state, state); await this.emit('change', this.state); }
type State = Circus.State;
1,532
async setState(state: State): Promise<void> { Object.assign(this.state, state); await this.emit('change', this.state); }
type State = { interrupted: boolean; };
1,533
async setState(state: State): Promise<void> { Object.assign(this.state, state); await this.emit('change', this.state); }
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,534
private _ensureMockConfig(f: Mock): MockFunctionConfig { let config = this._mockConfigRegistry.get(f); if (!config) { config = this._defaultMockConfig(); this._mockConfigRegistry.set(f, config); } return config; }
interface Mock<T extends FunctionLike = UnknownFunction> extends Function, MockInstance<T> { new (...args: Parameters<T>): ReturnType<T>; (...args: Parameters<T>): ReturnType<T>; }
1,535
private _ensureMockConfig(f: Mock): MockFunctionConfig { let config = this._mockConfigRegistry.get(f); if (!config) { config = this._defaultMockConfig(); this._mockConfigRegistry.set(f, config); } return config; }
type Mock<T extends FunctionLike = UnknownFunction> = JestMock<T>;
1,536
private _ensureMockConfig(f: Mock): MockFunctionConfig { let config = this._mockConfigRegistry.get(f); if (!config) { config = this._defaultMockConfig(); this._mockConfigRegistry.set(f, config); } return config; }
type Mock<T extends FunctionLike = UnknownFunction> = JestMock<T>;
1,537
function withImplementation( this: ModuleMocker, fn: T, callback: (() => void) | (() => Promise<unknown>), ): void | Promise<void> { // Remember previous mock implementation, then set new one const mockConfig = this._ensureMockConfig(f); const previousImplementation = mockConfig.mockImpl; mockConfig.mockImpl = fn; const returnedValue = callback(); if (isPromise(returnedValue)) { return returnedValue.then(() => { mockConfig.mockImpl = previousImplementation; }); } else { mockConfig.mockImpl = previousImplementation; } }
class ModuleMocker { private readonly _environmentGlobal: typeof globalThis; private _mockState: WeakMap<Mock, MockFunctionState>; private _mockConfigRegistry: WeakMap<Function, MockFunctionConfig>; private _spyState: Set<() => void>; private _invocationCallCounter: number; private _originalFn: WeakMap<Mock, Function>; /** * @see README.md * @param global Global object of the test environment, used to create * mocks */ constructor(global: typeof globalThis) { this._environmentGlobal = global; this._mockState = new WeakMap(); this._mockConfigRegistry = new WeakMap(); this._spyState = new Set(); this._invocationCallCounter = 1; this._originalFn = new WeakMap(); } private _getSlots(object?: Record<string, any>): Array<string> { if (!object) { return []; } const slots = new Set<string>(); const EnvObjectProto = this._environmentGlobal.Object.prototype; const EnvFunctionProto = this._environmentGlobal.Function.prototype; const EnvRegExpProto = this._environmentGlobal.RegExp.prototype; // Also check the builtins in the current context as they leak through // core node modules. const ObjectProto = Object.prototype; const FunctionProto = Function.prototype; const RegExpProto = RegExp.prototype; // Properties of Object.prototype, Function.prototype and RegExp.prototype // are never reported as slots while ( object != null && object !== EnvObjectProto && object !== EnvFunctionProto && object !== EnvRegExpProto && object !== ObjectProto && object !== FunctionProto && object !== RegExpProto ) { const ownNames = Object.getOwnPropertyNames(object); for (let i = 0; i < ownNames.length; i++) { const prop = ownNames[i]; if (!isReadonlyProp(object, prop)) { const propDesc = Object.getOwnPropertyDescriptor(object, prop); if ((propDesc !== undefined && !propDesc.get) || object.__esModule) { slots.add(prop); } } } object = Object.getPrototypeOf(object); } return Array.from(slots); } private _ensureMockConfig(f: Mock): MockFunctionConfig { let config = this._mockConfigRegistry.get(f); if (!config) { config = this._defaultMockConfig(); this._mockConfigRegistry.set(f, config); } return config; } private _ensureMockState<T extends UnknownFunction>( f: Mock<T>, ): MockFunctionState<T> { let state = this._mockState.get(f); if (!state) { state = this._defaultMockState(); this._mockState.set(f, state); } if (state.calls.length > 0) { state.lastCall = state.calls[state.calls.length - 1]; } return state; } private _defaultMockConfig(): MockFunctionConfig { return { mockImpl: undefined, mockName: 'jest.fn()', specificMockImpls: [], specificReturnValues: [], }; } private _defaultMockState(): MockFunctionState { return { calls: [], contexts: [], instances: [], invocationCallOrder: [], results: [], }; } private _makeComponent<T extends Record<string, any>>( metadata: MockMetadata<T, 'object'>, restore?: () => void, ): T; private _makeComponent<T extends Array<unknown>>( metadata: MockMetadata<T, 'array'>, restore?: () => void, ): T; private _makeComponent<T extends RegExp>( metadata: MockMetadata<T, 'regexp'>, restore?: () => void, ): T; private _makeComponent<T>( metadata: MockMetadata<T, 'constant' | 'collection' | 'null' | 'undefined'>, restore?: () => void, ): T; private _makeComponent<T extends UnknownFunction>( metadata: MockMetadata<T, 'function'>, restore?: () => void, ): Mock<T>; private _makeComponent<T extends UnknownFunction>( metadata: MockMetadata<T>, restore?: () => void, ): Record<string, any> | Array<unknown> | RegExp | T | Mock | undefined { if (metadata.type === 'object') { return new this._environmentGlobal.Object(); } else if (metadata.type === 'array') { return new this._environmentGlobal.Array(); } else if (metadata.type === 'regexp') { return new this._environmentGlobal.RegExp(''); } else if ( metadata.type === 'constant' || metadata.type === 'collection' || metadata.type === 'null' || metadata.type === 'undefined' ) { return metadata.value; } else if (metadata.type === 'function') { const prototype = (metadata.members && metadata.members.prototype && metadata.members.prototype.members) || {}; const prototypeSlots = this._getSlots(prototype); // eslint-disable-next-line @typescript-eslint/no-this-alias const mocker = this; const mockConstructor = matchArity(function ( this: ReturnType<T>, ...args: Parameters<T> ) { const mockState = mocker._ensureMockState(f); const mockConfig = mocker._ensureMockConfig(f); mockState.instances.push(this); mockState.contexts.push(this); mockState.calls.push(args); // Create and record an "incomplete" mock result immediately upon // calling rather than waiting for the mock to return. This avoids // issues caused by recursion where results can be recorded in the // wrong order. const mockResult: MockFunctionResult = { type: 'incomplete', value: undefined, }; mockState.results.push(mockResult); mockState.invocationCallOrder.push(mocker._invocationCallCounter++); // Will be set to the return value of the mock if an error is not thrown let finalReturnValue; // Will be set to the error that is thrown by the mock (if it throws) let thrownError; // Will be set to true if the mock throws an error. The presence of a // value in `thrownError` is not a 100% reliable indicator because a // function could throw a value of undefined. let callDidThrowError = false; try { // The bulk of the implementation is wrapped in an immediately // executed arrow function so the return value of the mock function // can be easily captured and recorded, despite the many separate // return points within the logic. finalReturnValue = (() => { if (this instanceof f) { // This is probably being called as a constructor prototypeSlots.forEach(slot => { // Copy prototype methods to the instance to make // it easier to interact with mock instance call and // return values if (prototype[slot].type === 'function') { // @ts-expect-error no index signature const protoImpl = this[slot]; // @ts-expect-error no index signature this[slot] = mocker.generateFromMetadata(prototype[slot]); // @ts-expect-error no index signature this[slot]._protoImpl = protoImpl; } }); // Run the mock constructor implementation const mockImpl = mockConfig.specificMockImpls.length ? mockConfig.specificMockImpls.shift() : mockConfig.mockImpl; return mockImpl && mockImpl.apply(this, arguments); } // If mockImplementationOnce()/mockImplementation() is last set, // implementation use the mock let specificMockImpl = mockConfig.specificMockImpls.shift(); if (specificMockImpl === undefined) { specificMockImpl = mockConfig.mockImpl; } if (specificMockImpl) { return specificMockImpl.apply(this, arguments); } // Otherwise use prototype implementation if (f._protoImpl) { return f._protoImpl.apply(this, arguments); } return undefined; })(); } catch (error) { // Store the thrown error so we can record it, then re-throw it. thrownError = error; callDidThrowError = true; throw error; } finally { // Record the result of the function. // NOTE: Intentionally NOT pushing/indexing into the array of mock // results here to avoid corrupting results data if mockClear() // is called during the execution of the mock. // @ts-expect-error reassigning 'incomplete' mockResult.type = callDidThrowError ? 'throw' : 'return'; mockResult.value = callDidThrowError ? thrownError : finalReturnValue; } return finalReturnValue; }, metadata.length || 0); const f = this._createMockFunction(metadata, mockConstructor) as Mock; f._isMockFunction = true; f.getMockImplementation = () => this._ensureMockConfig(f).mockImpl as T; if (typeof restore === 'function') { this._spyState.add(restore); } this._mockState.set(f, this._defaultMockState()); this._mockConfigRegistry.set(f, this._defaultMockConfig()); Object.defineProperty(f, 'mock', { configurable: false, enumerable: true, get: () => this._ensureMockState(f), set: val => this._mockState.set(f, val), }); f.mockClear = () => { this._mockState.delete(f); return f; }; f.mockReset = () => { f.mockClear(); const originalFn = this._originalFn.get(f); const originalMockImpl = { ...this._defaultMockConfig(), mockImpl: originalFn, }; this._mockConfigRegistry.set(f, originalMockImpl); return f; }; f.mockRestore = () => { f.mockReset(); return restore ? restore() : undefined; }; f.mockReturnValueOnce = (value: ReturnType<T>) => // next function call will return this value or default return value f.mockImplementationOnce(() => value); f.mockResolvedValueOnce = (value: ResolveType<T>) => f.mockImplementationOnce(() => this._environmentGlobal.Promise.resolve(value), ); f.mockRejectedValueOnce = (value: unknown) => f.mockImplementationOnce(() => this._environmentGlobal.Promise.reject(value), ); f.mockReturnValue = (value: ReturnType<T>) => // next function call will return specified return value or this one f.mockImplementation(() => value); f.mockResolvedValue = (value: ResolveType<T>) => f.mockImplementation(() => this._environmentGlobal.Promise.resolve(value), ); f.mockRejectedValue = (value: unknown) => f.mockImplementation(() => this._environmentGlobal.Promise.reject(value), ); f.mockImplementationOnce = (fn: T) => { // next function call will use this mock implementation return value // or default mock implementation return value const mockConfig = this._ensureMockConfig(f); mockConfig.specificMockImpls.push(fn); return f; }; f.withImplementation = withImplementation.bind(this); function withImplementation(fn: T, callback: () => void): void; function withImplementation( fn: T, callback: () => Promise<unknown>, ): Promise<void>; function withImplementation( this: ModuleMocker, fn: T, callback: (() => void) | (() => Promise<unknown>), ): void | Promise<void> { // Remember previous mock implementation, then set new one const mockConfig = this._ensureMockConfig(f); const previousImplementation = mockConfig.mockImpl; mockConfig.mockImpl = fn; const returnedValue = callback(); if (isPromise(returnedValue)) { return returnedValue.then(() => { mockConfig.mockImpl = previousImplementation; }); } else { mockConfig.mockImpl = previousImplementation; } } f.mockImplementation = (fn: T) => { // next function call will use mock implementation return value const mockConfig = this._ensureMockConfig(f); mockConfig.mockImpl = fn; return f; }; f.mockReturnThis = () => f.mockImplementation(function (this: ReturnType<T>) { return this; }); f.mockName = (name: string) => { if (name) { const mockConfig = this._ensureMockConfig(f); mockConfig.mockName = name; } return f; }; f.getMockName = () => { const mockConfig = this._ensureMockConfig(f); return mockConfig.mockName || 'jest.fn()'; }; if (metadata.mockImpl) { f.mockImplementation(metadata.mockImpl); } return f; } else { const unknownType = metadata.type || 'undefined type'; throw new Error(`Unrecognized type ${unknownType}`); } } private _createMockFunction<T extends UnknownFunction>( metadata: MockMetadata<T>, mockConstructor: Function, ): Function { let name = metadata.name; if (!name) { return mockConstructor; } // Preserve `name` property of mocked function. const boundFunctionPrefix = 'bound '; let bindCall = ''; // if-do-while for perf reasons. The common case is for the if to fail. if (name.startsWith(boundFunctionPrefix)) { do { name = name.substring(boundFunctionPrefix.length); // Call bind() just to alter the function name. bindCall = '.bind(null)'; } while (name && name.startsWith(boundFunctionPrefix)); } // Special case functions named `mockConstructor` to guard for infinite loops if (name === MOCK_CONSTRUCTOR_NAME) { return mockConstructor; } if ( // It's a syntax error to define functions with a reserved keyword as name RESERVED_KEYWORDS.has(name) || // It's also a syntax error to define functions with a name that starts with a number /^\d/.test(name) ) { name = `$${name}`; } // It's also a syntax error to define a function with a reserved character // as part of it's name. if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) { name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, '$'); } const body = `return function ${name}() {` + ` return ${MOCK_CONSTRUCTOR_NAME}.apply(this,arguments);` + `}${bindCall}`; const createConstructor = new this._environmentGlobal.Function( MOCK_CONSTRUCTOR_NAME, body, ); return createConstructor(mockConstructor); } private _generateMock<T>( metadata: MockMetadata<T>, callbacks: Array<Function>, refs: Record< number, Record<string, any> | Array<unknown> | RegExp | T | Mock | undefined >, ): Mocked<T> { // metadata not compatible but it's the same type, maybe problem with // overloading of _makeComponent and not _generateMock? // @ts-expect-error - unsure why TSC complains here? const mock = this._makeComponent(metadata); if (metadata.refID != null) { refs[metadata.refID] = mock; } this._getSlots(metadata.members).forEach(slot => { const slotMetadata = (metadata.members && metadata.members[slot]) || {}; if (slotMetadata.ref != null) { callbacks.push( (function (ref) { return () => (mock[slot] = refs[ref]); })(slotMetadata.ref), ); } else { mock[slot] = this._generateMock(slotMetadata, callbacks, refs); } }); if ( metadata.type !== 'undefined' && metadata.type !== 'null' && mock.prototype && typeof mock.prototype === 'object' ) { mock.prototype.constructor = mock; } return mock as Mocked<T>; } /** * Check whether the given property of an object has been already replaced. */ private _findReplacedProperty< T extends object, K extends PropertyLikeKeys<T>, >(object: T, propertyKey: K): ReplacedPropertyRestorer<T, K> | undefined { for (const spyState of this._spyState) { if ( 'object' in spyState && 'property' in spyState && spyState.object === object && spyState.property === propertyKey ) { return spyState as ReplacedPropertyRestorer<T, K>; } } return; } /** * @see README.md * @param metadata Metadata for the mock in the schema returned by the * getMetadata method of this module. */ generateFromMetadata<T>(metadata: MockMetadata<T>): Mocked<T> { const callbacks: Array<Function> = []; const refs = {}; const mock = this._generateMock<T>(metadata, callbacks, refs); callbacks.forEach(setter => setter()); return mock; } /** * @see README.md * @param component The component for which to retrieve metadata. */ getMetadata<T = unknown>( component: T, _refs?: Map<T, number>, ): MockMetadata<T> | null { const refs = _refs || new Map<T, number>(); const ref = refs.get(component); if (ref != null) { return {ref}; } const type = getType(component); if (!type) { return null; } const metadata: MockMetadata<T> = {type}; if ( type === 'constant' || type === 'collection' || type === 'undefined' || type === 'null' ) { metadata.value = component; return metadata; } else if (type === 'function') { // @ts-expect-error component is a function so it has a name, but not // necessarily a string: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#function_names_in_classes const componentName = component.name; if (typeof componentName === 'string') { metadata.name = componentName; } if (this.isMockFunction(component)) { metadata.mockImpl = component.getMockImplementation() as T; } } metadata.refID = refs.size; refs.set(component, metadata.refID); let members: Record<string, MockMetadata<T>> | null = null; // Leave arrays alone if (type !== 'array') { // @ts-expect-error component is object this._getSlots(component).forEach(slot => { if ( type === 'function' && this.isMockFunction(component) && slot.match(/^mock/) ) { return; } // @ts-expect-error no index signature const slotMetadata = this.getMetadata<T>(component[slot], refs); if (slotMetadata) { if (!members) { members = {}; } members[slot] = slotMetadata; } }); } if (members) { metadata.members = members; } return metadata; } isMockFunction<T extends FunctionLike = UnknownFunction>( fn: MockInstance<T>, ): fn is MockInstance<T>; isMockFunction<P extends Array<unknown>, R>( fn: (...args: P) => R, ): fn is Mock<(...args: P) => R>; isMockFunction(fn: unknown): fn is Mock<UnknownFunction>; isMockFunction(fn: unknown): fn is Mock<UnknownFunction> { return fn != null && (fn as Mock)._isMockFunction === true; } fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T> { const length = implementation ? implementation.length : 0; const fn = this._makeComponent<T>({ length, type: 'function', }); if (implementation) { fn.mockImplementation(implementation); } return fn; } spyOn< T extends object, K extends PropertyLikeKeys<T>, V extends Required<T>[K], A extends 'get' | 'set', >( object: T, methodKey: K, accessType: A, ): A extends 'get' ? SpiedGetter<V> : A extends 'set' ? SpiedSetter<V> : never; spyOn< T extends object, K extends ConstructorLikeKeys<T> | MethodLikeKeys<T>, V extends Required<T>[K], >( object: T, methodKey: K, ): V extends ClassLike | FunctionLike ? Spied<V> : never; spyOn<T extends object>( object: T, methodKey: keyof T, accessType?: 'get' | 'set', ): MockInstance { if (typeof object !== 'object' && typeof object !== 'function') { throw new Error( `Cannot use spyOn on a primitive value; ${this._typeOf(object)} given`, ); } if (!object) { throw new Error( `spyOn could not find an object to spy on for ${String(methodKey)}`, ); } if (!methodKey) { throw new Error('No property name supplied'); } if (accessType) { return this._spyOnProperty(object, methodKey, accessType); } const original = object[methodKey]; if (!this.isMockFunction(original)) { if (typeof original !== 'function') { throw new Error( `Cannot spy on the ${String( methodKey, )} property because it is not a function; ${this._typeOf( original, )} given instead.${ typeof original !== 'object' ? ` If you are trying to mock a property, use \`jest.replaceProperty(object, '${String( methodKey, )}', value)\` instead.` : '' }`, ); } const isMethodOwner = Object.prototype.hasOwnProperty.call( object, methodKey, ); let descriptor = Object.getOwnPropertyDescriptor(object, methodKey); let proto = Object.getPrototypeOf(object); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, methodKey); proto = Object.getPrototypeOf(proto); } let mock: Mock; if (descriptor && descriptor.get) { const originalGet = descriptor.get; mock = this._makeComponent({type: 'function'}, () => { descriptor!.get = originalGet; Object.defineProperty(object, methodKey, descriptor!); }); descriptor.get = () => mock; Object.defineProperty(object, methodKey, descriptor); } else { mock = this._makeComponent({type: 'function'}, () => { if (isMethodOwner) { object[methodKey] = original; } else { delete object[methodKey]; } }); // @ts-expect-error overriding original method with a Mock object[methodKey] = mock; } mock.mockImplementation(function (this: unknown) { return original.apply(this, arguments); }); } this._originalFn.set(object[methodKey] as Mock, original); return object[methodKey] as Mock; } private _spyOnProperty<T extends object>( object: T, propertyKey: keyof T, accessType: 'get' | 'set', ): MockInstance { let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey); let proto = Object.getPrototypeOf(object); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey); proto = Object.getPrototypeOf(proto); } if (!descriptor) { throw new Error(`${String(propertyKey)} property does not exist`); } if (!descriptor.configurable) { throw new Error(`${String(propertyKey)} is not declared configurable`); } if (!descriptor[accessType]) { throw new Error( `Property ${String( propertyKey, )} does not have access type ${accessType}`, ); } const original = descriptor[accessType]; if (!this.isMockFunction(original)) { if (typeof original !== 'function') { throw new Error( `Cannot spy on the ${String( propertyKey, )} property because it is not a function; ${this._typeOf( original, )} given instead.${ typeof original !== 'object' ? ` If you are trying to mock a property, use \`jest.replaceProperty(object, '${String( propertyKey, )}', value)\` instead.` : '' }`, ); } descriptor[accessType] = this._makeComponent({type: 'function'}, () => { // @ts-expect-error: mock is assignable descriptor![accessType] = original; Object.defineProperty(object, propertyKey, descriptor!); }); (descriptor[accessType] as Mock).mockImplementation(function ( this: unknown, ) { // @ts-expect-error - wrong context return original.apply(this, arguments); }); } Object.defineProperty(object, propertyKey, descriptor); return descriptor[accessType] as Mock; } replaceProperty< T extends object, K extends PropertyLikeKeys<T>, V extends T[K], >(object: T, propertyKey: K, value: V): Replaced<T[K]> { if (object === undefined || object == null) { throw new Error( `replaceProperty could not find an object on which to replace ${String( propertyKey, )}`, ); } if (propertyKey === undefined || propertyKey === null) { throw new Error('No property name supplied'); } if (typeof object !== 'object') { throw new Error( `Cannot mock property on a non-object value; ${this._typeOf( object, )} given`, ); } let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey); let proto = Object.getPrototypeOf(object); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey); proto = Object.getPrototypeOf(proto); } if (!descriptor) { throw new Error(`${String(propertyKey)} property does not exist`); } if (!descriptor.configurable) { throw new Error(`${String(propertyKey)} is not declared configurable`); } if (descriptor.get !== undefined) { throw new Error( `Cannot mock the ${String( propertyKey, )} property because it has a getter. Use \`jest.spyOn(object, '${String( propertyKey, )}', 'get').mockReturnValue(value)\` instead.`, ); } if (descriptor.set !== undefined) { throw new Error( `Cannot mock the ${String( propertyKey, )} property because it has a setter. Use \`jest.spyOn(object, '${String( propertyKey, )}', 'set').mockReturnValue(value)\` instead.`, ); } if (typeof descriptor.value === 'function') { throw new Error( `Cannot mock the ${String( propertyKey, )} property because it is a function. Use \`jest.spyOn(object, '${String( propertyKey, )}')\` instead.`, ); } const existingRestore = this._findReplacedProperty(object, propertyKey); if (existingRestore) { return existingRestore.replaced.replaceValue(value); } const isPropertyOwner = Object.prototype.hasOwnProperty.call( object, propertyKey, ); const originalValue = descriptor.value; const restore: ReplacedPropertyRestorer<T, K> = () => { if (isPropertyOwner) { object[propertyKey] = originalValue; } else { delete object[propertyKey]; } }; const replaced: Replaced<T[K]> = { replaceValue: value => { object[propertyKey] = value; return replaced; }, restore: () => { restore(); this._spyState.delete(restore); }, }; restore.object = object; restore.property = propertyKey; restore.replaced = replaced; this._spyState.add(restore); return replaced.replaceValue(value); } clearAllMocks(): void { this._mockState = new WeakMap(); } resetAllMocks(): void { this._spyState.forEach(reset => reset()); this._mockConfigRegistry = new WeakMap(); this._mockState = new WeakMap(); } restoreAllMocks(): void { this._spyState.forEach(restore => restore()); this._spyState = new Set(); } private _typeOf(value: unknown): string { return value == null ? `${value}` : typeof value; } mocked<T extends object>(source: T, options?: {shallow: false}): Mocked<T>; mocked<T extends object>( source: T, options: {shallow: true}, ): MockedShallow<T>; mocked<T extends object>( source: T, _options?: {shallow: boolean}, ): Mocked<T> | MockedShallow<T> { return source as Mocked<T> | MockedShallow<T>; } }
1,538
spyOn< T extends object, K extends PropertyLikeKeys<T>, V extends Required<T>[K], A extends 'get' | 'set', >( object: T, methodKey: K, accessType: A, ): A extends 'get' ? SpiedGetter<V> : A extends 'set' ? SpiedSetter<V> : never
type A = string;
1,539
spyOn< T extends object, K extends PropertyLikeKeys<T>, V extends Required<T>[K], A extends 'get' | 'set', >( object: T, methodKey: K, accessType: A, ): A extends 'get' ? SpiedGetter<V> : A extends 'set' ? SpiedSetter<V> : never
type A = string;
1,540
spyOn< T extends object, K extends PropertyLikeKeys<T>, V extends Required<T>[K], A extends 'get' | 'set', >( object: T, methodKey: K, accessType: A, ): A extends 'get' ? SpiedGetter<V> : A extends 'set' ? SpiedSetter<V> : never
class A { get a() { return 'a'; } get b() { return {c: 'c'}; } }
1,541
( this: TesterContext, a: any, b: any, customTesters: Array<Tester>, ) => boolean | undefined
interface TesterContext { equals: EqualsFunction; }
1,542
constructor(config: JestEnvironmentConfig, context: EnvironmentContext)
type EnvironmentContext = { console: Console; docblockPragmas: Record<string, string | Array<string>>; testPath: string; };
1,543
constructor(config: JestEnvironmentConfig, context: EnvironmentContext)
interface JestEnvironmentConfig { projectConfig: Config.ProjectConfig; globalConfig: Config.GlobalConfig; }
1,544
( g: Global, table: Global.EachTable, ...data: Global.TemplateData ) => { const bindingWithArray = data.length === 0; const bindingWithTemplate = Array.isArray(table) && !!(table as any).raw; if (!bindingWithArray && !bindingWithTemplate) { throw new Error( '`.each` must only be called with an Array or Tagged Template Literal.', ); } const test = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test)(table, ...data)(title, test, timeout); test.skip = bind(g.test.skip)(table, ...data); test.only = bind(g.test.only)(table, ...data); const testConcurrent = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test.concurrent)(table, ...data)(title, test, timeout); test.concurrent = testConcurrent; testConcurrent.only = bind(g.test.concurrent.only)(table, ...data); testConcurrent.skip = bind(g.test.concurrent.skip)(table, ...data); const it = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.it)(table, ...data)(title, test, timeout); it.skip = bind(g.it.skip)(table, ...data); it.only = bind(g.it.only)(table, ...data); it.concurrent = testConcurrent; const xit = bind(g.xit)(table, ...data); const fit = bind(g.fit)(table, ...data); const xtest = bind(g.xtest)(table, ...data); const describe = ( title: string, suite: Global.EachTestFn<Global.BlockFn>, timeout?: number, ) => bind(g.describe, false)(table, ...data)(title, suite, timeout); describe.skip = bind(g.describe.skip, false)(table, ...data); describe.only = bind(g.describe.only, false)(table, ...data); const fdescribe = bind(g.fdescribe, false)(table, ...data); const xdescribe = bind(g.xdescribe, false)(table, ...data); return {describe, fdescribe, fit, it, test, xdescribe, xit, xtest}; }
interface Global { expect: JestExpect; jasmine: Jasmine; }
1,545
( g: Global, table: Global.EachTable, ...data: Global.TemplateData ) => { const bindingWithArray = data.length === 0; const bindingWithTemplate = Array.isArray(table) && !!(table as any).raw; if (!bindingWithArray && !bindingWithTemplate) { throw new Error( '`.each` must only be called with an Array or Tagged Template Literal.', ); } const test = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test)(table, ...data)(title, test, timeout); test.skip = bind(g.test.skip)(table, ...data); test.only = bind(g.test.only)(table, ...data); const testConcurrent = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test.concurrent)(table, ...data)(title, test, timeout); test.concurrent = testConcurrent; testConcurrent.only = bind(g.test.concurrent.only)(table, ...data); testConcurrent.skip = bind(g.test.concurrent.skip)(table, ...data); const it = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.it)(table, ...data)(title, test, timeout); it.skip = bind(g.it.skip)(table, ...data); it.only = bind(g.it.only)(table, ...data); it.concurrent = testConcurrent; const xit = bind(g.xit)(table, ...data); const fit = bind(g.fit)(table, ...data); const xtest = bind(g.xtest)(table, ...data); const describe = ( title: string, suite: Global.EachTestFn<Global.BlockFn>, timeout?: number, ) => bind(g.describe, false)(table, ...data)(title, suite, timeout); describe.skip = bind(g.describe.skip, false)(table, ...data); describe.only = bind(g.describe.only, false)(table, ...data); const fdescribe = bind(g.fdescribe, false)(table, ...data); const xdescribe = bind(g.xdescribe, false)(table, ...data); return {describe, fdescribe, fit, it, test, xdescribe, xit, xtest}; }
interface Global { [testTimeoutSymbol]: number; }
1,546
( g: Global, table: Global.EachTable, ...data: Global.TemplateData ) => { const bindingWithArray = data.length === 0; const bindingWithTemplate = Array.isArray(table) && !!(table as any).raw; if (!bindingWithArray && !bindingWithTemplate) { throw new Error( '`.each` must only be called with an Array or Tagged Template Literal.', ); } const test = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test)(table, ...data)(title, test, timeout); test.skip = bind(g.test.skip)(table, ...data); test.only = bind(g.test.only)(table, ...data); const testConcurrent = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test.concurrent)(table, ...data)(title, test, timeout); test.concurrent = testConcurrent; testConcurrent.only = bind(g.test.concurrent.only)(table, ...data); testConcurrent.skip = bind(g.test.concurrent.skip)(table, ...data); const it = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.it)(table, ...data)(title, test, timeout); it.skip = bind(g.it.skip)(table, ...data); it.only = bind(g.it.only)(table, ...data); it.concurrent = testConcurrent; const xit = bind(g.xit)(table, ...data); const fit = bind(g.fit)(table, ...data); const xtest = bind(g.xtest)(table, ...data); const describe = ( title: string, suite: Global.EachTestFn<Global.BlockFn>, timeout?: number, ) => bind(g.describe, false)(table, ...data)(title, suite, timeout); describe.skip = bind(g.describe.skip, false)(table, ...data); describe.only = bind(g.describe.only, false)(table, ...data); const fdescribe = bind(g.fdescribe, false)(table, ...data); const xdescribe = bind(g.xdescribe, false)(table, ...data); return {describe, fdescribe, fit, it, test, xdescribe, xit, xtest}; }
interface Global { [STATE_SYM]: Circus.State; [RETRY_TIMES]: string; [TEST_TIMEOUT_SYMBOL]: number; [LOG_ERRORS_BEFORE_RETRY]: boolean; }
1,547
( g: Global, table: Global.EachTable, ...data: Global.TemplateData ) => { const bindingWithArray = data.length === 0; const bindingWithTemplate = Array.isArray(table) && !!(table as any).raw; if (!bindingWithArray && !bindingWithTemplate) { throw new Error( '`.each` must only be called with an Array or Tagged Template Literal.', ); } const test = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test)(table, ...data)(title, test, timeout); test.skip = bind(g.test.skip)(table, ...data); test.only = bind(g.test.only)(table, ...data); const testConcurrent = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test.concurrent)(table, ...data)(title, test, timeout); test.concurrent = testConcurrent; testConcurrent.only = bind(g.test.concurrent.only)(table, ...data); testConcurrent.skip = bind(g.test.concurrent.skip)(table, ...data); const it = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.it)(table, ...data)(title, test, timeout); it.skip = bind(g.it.skip)(table, ...data); it.only = bind(g.it.only)(table, ...data); it.concurrent = testConcurrent; const xit = bind(g.xit)(table, ...data); const fit = bind(g.fit)(table, ...data); const xtest = bind(g.xtest)(table, ...data); const describe = ( title: string, suite: Global.EachTestFn<Global.BlockFn>, timeout?: number, ) => bind(g.describe, false)(table, ...data)(title, suite, timeout); describe.skip = bind(g.describe.skip, false)(table, ...data); describe.only = bind(g.describe.only, false)(table, ...data); const fdescribe = bind(g.fdescribe, false)(table, ...data); const xdescribe = bind(g.xdescribe, false)(table, ...data); return {describe, fdescribe, fit, it, test, xdescribe, xit, xtest}; }
type Global = Global.Global;
1,548
( g: Global, table: Global.EachTable, ...data: Global.TemplateData ) => { const bindingWithArray = data.length === 0; const bindingWithTemplate = Array.isArray(table) && !!(table as any).raw; if (!bindingWithArray && !bindingWithTemplate) { throw new Error( '`.each` must only be called with an Array or Tagged Template Literal.', ); } const test = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test)(table, ...data)(title, test, timeout); test.skip = bind(g.test.skip)(table, ...data); test.only = bind(g.test.only)(table, ...data); const testConcurrent = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.test.concurrent)(table, ...data)(title, test, timeout); test.concurrent = testConcurrent; testConcurrent.only = bind(g.test.concurrent.only)(table, ...data); testConcurrent.skip = bind(g.test.concurrent.skip)(table, ...data); const it = ( title: string, test: Global.EachTestFn<Global.TestFn>, timeout?: number, ) => bind(g.it)(table, ...data)(title, test, timeout); it.skip = bind(g.it.skip)(table, ...data); it.only = bind(g.it.only)(table, ...data); it.concurrent = testConcurrent; const xit = bind(g.xit)(table, ...data); const fit = bind(g.fit)(table, ...data); const xtest = bind(g.xtest)(table, ...data); const describe = ( title: string, suite: Global.EachTestFn<Global.BlockFn>, timeout?: number, ) => bind(g.describe, false)(table, ...data)(title, suite, timeout); describe.skip = bind(g.describe.skip, false)(table, ...data); describe.only = bind(g.describe.only, false)(table, ...data); const fdescribe = bind(g.fdescribe, false)(table, ...data); const xdescribe = bind(g.xdescribe, false)(table, ...data); return {describe, fdescribe, fit, it, test, xdescribe, xit, xtest}; }
interface Global extends GlobalAdditions, Omit<typeof globalThis, keyof GlobalAdditions> { [extras: PropertyKey]: unknown; }
1,549
(g: Global) => (table: Global.EachTable, ...data: Global.TemplateData) => install(g, table, ...data)
interface Global { expect: JestExpect; jasmine: Jasmine; }
1,550
(g: Global) => (table: Global.EachTable, ...data: Global.TemplateData) => install(g, table, ...data)
interface Global { [testTimeoutSymbol]: number; }
1,551
(g: Global) => (table: Global.EachTable, ...data: Global.TemplateData) => install(g, table, ...data)
interface Global { [STATE_SYM]: Circus.State; [RETRY_TIMES]: string; [TEST_TIMEOUT_SYMBOL]: number; [LOG_ERRORS_BEFORE_RETRY]: boolean; }
1,552
(g: Global) => (table: Global.EachTable, ...data: Global.TemplateData) => install(g, table, ...data)
type Global = Global.Global;
1,553
(g: Global) => (table: Global.EachTable, ...data: Global.TemplateData) => install(g, table, ...data)
interface Global extends GlobalAdditions, Omit<typeof globalThis, keyof GlobalAdditions> { [extras: PropertyKey]: unknown; }
1,554
function bind<EachCallback extends Global.TestCallback>( cb: GlobalCallback, supportsDone = true, needsEachError = false, ): Global.EachTestFn<any> { const bindWrap = ( table: Global.EachTable, ...taggedTemplateData: Global.TemplateData ) => { const error = new ErrorWithStack(undefined, bindWrap); return function eachBind( title: Global.BlockNameLike, test: Global.EachTestFn<EachCallback>, timeout?: number, ): void { title = convertDescriptorToString(title); try { const tests = isArrayTable(taggedTemplateData) ? buildArrayTests(title, table) : buildTemplateTests(title, table, taggedTemplateData); return tests.forEach(row => needsEachError ? cb( row.title, applyArguments(supportsDone, row.arguments, test), timeout, error, ) : cb( row.title, applyArguments(supportsDone, row.arguments, test), timeout, ), ); } catch (e: any) { const err = new Error(e.message); err.stack = error.stack?.replace(/^Error: /s, `Error: ${e.message}`); return cb(title, () => { throw err; }); } }; }; return bindWrap; }
type GlobalCallback = ( testName: string, fn: Global.ConcurrentTestFn, timeout?: number, eachError?: Error, ) => void;
1,555
(matches: Headings, key: string) => matches.concat(title.match(new RegExp(`\\$${key}[\\.\\w]*`, 'g')) || [])
type Headings = Array<string>;
1,556
(template: Template) => (title: string, match: string) => { const keyPath = match.replace('$', '').split('.'); const value = getPath(template, keyPath); if (isPrimitive(value)) { return title.replace(match, String(value)); } return title.replace(match, pretty(value, {maxDepth: 1, min: true})); }
type Template = Record<string, unknown>;
1,557
function getPath( template: Template, [head, ...tail]: Array<string>, ): unknown { if (!head || !Object.prototype.hasOwnProperty.call(template, head)) return template; return getPath(template[head] as Template, tail); }
type Template = Record<string, unknown>;
1,558
( results: AggregatedResult, ) => AggregatedResult
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,559
( aggregatedResults: AggregatedResult, testResult: TestResult, ): void => { // `todos` are new as of Jest 24, and not all runners return it. // Set it to `0` to avoid `NaN` if (!testResult.numTodoTests) { testResult.numTodoTests = 0; } aggregatedResults.testResults.push(testResult); aggregatedResults.numTotalTests += testResult.numPassingTests + testResult.numFailingTests + testResult.numPendingTests + testResult.numTodoTests; aggregatedResults.numFailedTests += testResult.numFailingTests; aggregatedResults.numPassedTests += testResult.numPassingTests; aggregatedResults.numPendingTests += testResult.numPendingTests; aggregatedResults.numTodoTests += testResult.numTodoTests; if (testResult.testExecError) { aggregatedResults.numRuntimeErrorTestSuites++; } if (testResult.skipped) { aggregatedResults.numPendingTestSuites++; } else if (testResult.numFailingTests > 0 || testResult.testExecError) { aggregatedResults.numFailedTestSuites++; } else { aggregatedResults.numPassedTestSuites++; } // Snapshot data if (testResult.snapshot.added) { aggregatedResults.snapshot.filesAdded++; } if (testResult.snapshot.fileDeleted) { aggregatedResults.snapshot.filesRemoved++; } if (testResult.snapshot.unmatched) { aggregatedResults.snapshot.filesUnmatched++; } if (testResult.snapshot.updated) { aggregatedResults.snapshot.filesUpdated++; } aggregatedResults.snapshot.added += testResult.snapshot.added; aggregatedResults.snapshot.matched += testResult.snapshot.matched; aggregatedResults.snapshot.unchecked += testResult.snapshot.unchecked; if ( testResult.snapshot.uncheckedKeys != null && testResult.snapshot.uncheckedKeys.length > 0 ) { aggregatedResults.snapshot.uncheckedKeysByFile.push({ filePath: testResult.testFilePath, keys: testResult.snapshot.uncheckedKeys, }); } aggregatedResults.snapshot.unmatched += testResult.snapshot.unmatched; aggregatedResults.snapshot.updated += testResult.snapshot.updated; aggregatedResults.snapshot.total += testResult.snapshot.added + testResult.snapshot.matched + testResult.snapshot.unmatched + testResult.snapshot.updated; }
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,560
( aggregatedResults: AggregatedResult, testResult: TestResult, ): void => { // `todos` are new as of Jest 24, and not all runners return it. // Set it to `0` to avoid `NaN` if (!testResult.numTodoTests) { testResult.numTodoTests = 0; } aggregatedResults.testResults.push(testResult); aggregatedResults.numTotalTests += testResult.numPassingTests + testResult.numFailingTests + testResult.numPendingTests + testResult.numTodoTests; aggregatedResults.numFailedTests += testResult.numFailingTests; aggregatedResults.numPassedTests += testResult.numPassingTests; aggregatedResults.numPendingTests += testResult.numPendingTests; aggregatedResults.numTodoTests += testResult.numTodoTests; if (testResult.testExecError) { aggregatedResults.numRuntimeErrorTestSuites++; } if (testResult.skipped) { aggregatedResults.numPendingTestSuites++; } else if (testResult.numFailingTests > 0 || testResult.testExecError) { aggregatedResults.numFailedTestSuites++; } else { aggregatedResults.numPassedTestSuites++; } // Snapshot data if (testResult.snapshot.added) { aggregatedResults.snapshot.filesAdded++; } if (testResult.snapshot.fileDeleted) { aggregatedResults.snapshot.filesRemoved++; } if (testResult.snapshot.unmatched) { aggregatedResults.snapshot.filesUnmatched++; } if (testResult.snapshot.updated) { aggregatedResults.snapshot.filesUpdated++; } aggregatedResults.snapshot.added += testResult.snapshot.added; aggregatedResults.snapshot.matched += testResult.snapshot.matched; aggregatedResults.snapshot.unchecked += testResult.snapshot.unchecked; if ( testResult.snapshot.uncheckedKeys != null && testResult.snapshot.uncheckedKeys.length > 0 ) { aggregatedResults.snapshot.uncheckedKeysByFile.push({ filePath: testResult.testFilePath, keys: testResult.snapshot.uncheckedKeys, }); } aggregatedResults.snapshot.unmatched += testResult.snapshot.unmatched; aggregatedResults.snapshot.updated += testResult.snapshot.updated; aggregatedResults.snapshot.total += testResult.snapshot.added + testResult.snapshot.matched + testResult.snapshot.unmatched + testResult.snapshot.updated; }
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,561
( aggregatedResults: AggregatedResult, testResult: TestResult, ): void => { // `todos` are new as of Jest 24, and not all runners return it. // Set it to `0` to avoid `NaN` if (!testResult.numTodoTests) { testResult.numTodoTests = 0; } aggregatedResults.testResults.push(testResult); aggregatedResults.numTotalTests += testResult.numPassingTests + testResult.numFailingTests + testResult.numPendingTests + testResult.numTodoTests; aggregatedResults.numFailedTests += testResult.numFailingTests; aggregatedResults.numPassedTests += testResult.numPassingTests; aggregatedResults.numPendingTests += testResult.numPendingTests; aggregatedResults.numTodoTests += testResult.numTodoTests; if (testResult.testExecError) { aggregatedResults.numRuntimeErrorTestSuites++; } if (testResult.skipped) { aggregatedResults.numPendingTestSuites++; } else if (testResult.numFailingTests > 0 || testResult.testExecError) { aggregatedResults.numFailedTestSuites++; } else { aggregatedResults.numPassedTestSuites++; } // Snapshot data if (testResult.snapshot.added) { aggregatedResults.snapshot.filesAdded++; } if (testResult.snapshot.fileDeleted) { aggregatedResults.snapshot.filesRemoved++; } if (testResult.snapshot.unmatched) { aggregatedResults.snapshot.filesUnmatched++; } if (testResult.snapshot.updated) { aggregatedResults.snapshot.filesUpdated++; } aggregatedResults.snapshot.added += testResult.snapshot.added; aggregatedResults.snapshot.matched += testResult.snapshot.matched; aggregatedResults.snapshot.unchecked += testResult.snapshot.unchecked; if ( testResult.snapshot.uncheckedKeys != null && testResult.snapshot.uncheckedKeys.length > 0 ) { aggregatedResults.snapshot.uncheckedKeysByFile.push({ filePath: testResult.testFilePath, keys: testResult.snapshot.uncheckedKeys, }); } aggregatedResults.snapshot.unmatched += testResult.snapshot.unmatched; aggregatedResults.snapshot.updated += testResult.snapshot.updated; aggregatedResults.snapshot.total += testResult.snapshot.added + testResult.snapshot.matched + testResult.snapshot.unmatched + testResult.snapshot.updated; }
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,562
( testResult: TestResult, codeCoverageFormatter?: CodeCoverageFormatter, reporter?: CodeCoverageReporter, ): FormattedTestResult => { if (testResult.testExecError) { const now = Date.now(); return { assertionResults: testResult.testResults, coverage: {}, endTime: now, message: testResult.failureMessage ?? testResult.testExecError.message, name: testResult.testFilePath, startTime: now, status: 'failed', summary: '', }; } if (testResult.skipped) { const now = Date.now(); return { assertionResults: testResult.testResults, coverage: {}, endTime: now, message: testResult.failureMessage ?? '', name: testResult.testFilePath, startTime: now, status: 'skipped', summary: '', }; } const allTestsExecuted = testResult.numPendingTests === 0; const allTestsPassed = testResult.numFailingTests === 0; return { assertionResults: testResult.testResults, coverage: codeCoverageFormatter != null ? codeCoverageFormatter(testResult.coverage, reporter) : testResult.coverage, endTime: testResult.perfStats.end, message: testResult.failureMessage ?? '', name: testResult.testFilePath, startTime: testResult.perfStats.start, status: allTestsPassed ? allTestsExecuted ? 'passed' : 'focused' : 'failed', summary: '', }; }
type CodeCoverageReporter = unknown;
1,563
( testResult: TestResult, codeCoverageFormatter?: CodeCoverageFormatter, reporter?: CodeCoverageReporter, ): FormattedTestResult => { if (testResult.testExecError) { const now = Date.now(); return { assertionResults: testResult.testResults, coverage: {}, endTime: now, message: testResult.failureMessage ?? testResult.testExecError.message, name: testResult.testFilePath, startTime: now, status: 'failed', summary: '', }; } if (testResult.skipped) { const now = Date.now(); return { assertionResults: testResult.testResults, coverage: {}, endTime: now, message: testResult.failureMessage ?? '', name: testResult.testFilePath, startTime: now, status: 'skipped', summary: '', }; } const allTestsExecuted = testResult.numPendingTests === 0; const allTestsPassed = testResult.numFailingTests === 0; return { assertionResults: testResult.testResults, coverage: codeCoverageFormatter != null ? codeCoverageFormatter(testResult.coverage, reporter) : testResult.coverage, endTime: testResult.perfStats.end, message: testResult.failureMessage ?? '', name: testResult.testFilePath, startTime: testResult.perfStats.start, status: allTestsPassed ? allTestsExecuted ? 'passed' : 'focused' : 'failed', summary: '', }; }
type CodeCoverageFormatter = ( coverage: CoverageMapData | null | undefined, reporter: CodeCoverageReporter, ) => Record<string, unknown> | null | undefined;
1,564
( testResult: TestResult, codeCoverageFormatter?: CodeCoverageFormatter, reporter?: CodeCoverageReporter, ): FormattedTestResult => { if (testResult.testExecError) { const now = Date.now(); return { assertionResults: testResult.testResults, coverage: {}, endTime: now, message: testResult.failureMessage ?? testResult.testExecError.message, name: testResult.testFilePath, startTime: now, status: 'failed', summary: '', }; } if (testResult.skipped) { const now = Date.now(); return { assertionResults: testResult.testResults, coverage: {}, endTime: now, message: testResult.failureMessage ?? '', name: testResult.testFilePath, startTime: now, status: 'skipped', summary: '', }; } const allTestsExecuted = testResult.numPendingTests === 0; const allTestsPassed = testResult.numFailingTests === 0; return { assertionResults: testResult.testResults, coverage: codeCoverageFormatter != null ? codeCoverageFormatter(testResult.coverage, reporter) : testResult.coverage, endTime: testResult.perfStats.end, message: testResult.failureMessage ?? '', name: testResult.testFilePath, startTime: testResult.perfStats.start, status: allTestsPassed ? allTestsExecuted ? 'passed' : 'focused' : 'failed', summary: '', }; }
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,565
( testResult: TestResult, codeCoverageFormatter?: CodeCoverageFormatter, reporter?: CodeCoverageReporter, ): FormattedTestResult => { if (testResult.testExecError) { const now = Date.now(); return { assertionResults: testResult.testResults, coverage: {}, endTime: now, message: testResult.failureMessage ?? testResult.testExecError.message, name: testResult.testFilePath, startTime: now, status: 'failed', summary: '', }; } if (testResult.skipped) { const now = Date.now(); return { assertionResults: testResult.testResults, coverage: {}, endTime: now, message: testResult.failureMessage ?? '', name: testResult.testFilePath, startTime: now, status: 'skipped', summary: '', }; } const allTestsExecuted = testResult.numPendingTests === 0; const allTestsPassed = testResult.numFailingTests === 0; return { assertionResults: testResult.testResults, coverage: codeCoverageFormatter != null ? codeCoverageFormatter(testResult.coverage, reporter) : testResult.coverage, endTime: testResult.perfStats.end, message: testResult.failureMessage ?? '', name: testResult.testFilePath, startTime: testResult.perfStats.start, status: allTestsPassed ? allTestsExecuted ? 'passed' : 'focused' : 'failed', summary: '', }; }
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,566
function formatTestResults( results: AggregatedResult, codeCoverageFormatter?: CodeCoverageFormatter, reporter?: CodeCoverageReporter, ): FormattedTestResults { const testResults = results.testResults.map(testResult => formatTestResult(testResult, codeCoverageFormatter, reporter), ); return {...results, testResults}; }
type CodeCoverageReporter = unknown;
1,567
function formatTestResults( results: AggregatedResult, codeCoverageFormatter?: CodeCoverageFormatter, reporter?: CodeCoverageReporter, ): FormattedTestResults { const testResults = results.testResults.map(testResult => formatTestResult(testResult, codeCoverageFormatter, reporter), ); return {...results, testResults}; }
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,568
function formatTestResults( results: AggregatedResult, codeCoverageFormatter?: CodeCoverageFormatter, reporter?: CodeCoverageReporter, ): FormattedTestResults { const testResults = results.testResults.map(testResult => formatTestResult(testResult, codeCoverageFormatter, reporter), ); return {...results, testResults}; }
type CodeCoverageFormatter = ( coverage: CoverageMapData | null | undefined, reporter: CodeCoverageReporter, ) => Record<string, unknown> | null | undefined;
1,569
(event: ChangeEvent) => void
type ChangeEvent = { eventsQueue: EventsQueue; hasteFS: HasteFS; moduleMap: ModuleMap; };
1,570
static async create(options: Options): Promise<IHasteMap> { if (options.hasteMapModulePath) { const CustomHasteMap = require(options.hasteMapModulePath); return new CustomHasteMap(options); } const hasteMap = new HasteMap(options); await hasteMap.setupCachePath(options); return hasteMap; }
interface Options extends ShouldInstrumentOptions, CallerTransformOptions { isInternalModule?: boolean; }
1,571
static async create(options: Options): Promise<IHasteMap> { if (options.hasteMapModulePath) { const CustomHasteMap = require(options.hasteMapModulePath); return new CustomHasteMap(options); } const hasteMap = new HasteMap(options); await hasteMap.setupCachePath(options); return hasteMap; }
type Options = { clearTimeout: (typeof globalThis)['clearTimeout']; fail: (error: Error) => void; onException: (error: Error) => void; queueableFns: Array<QueueableFn>; setTimeout: (typeof globalThis)['setTimeout']; userContext: unknown; };
1,572
static async create(options: Options): Promise<IHasteMap> { if (options.hasteMapModulePath) { const CustomHasteMap = require(options.hasteMapModulePath); return new CustomHasteMap(options); } const hasteMap = new HasteMap(options); await hasteMap.setupCachePath(options); return hasteMap; }
type Options = { matcherName: string; passed: boolean; actual?: any; error?: any; expected?: any; message?: string | null; };
1,573
static async create(options: Options): Promise<IHasteMap> { if (options.hasteMapModulePath) { const CustomHasteMap = require(options.hasteMapModulePath); return new CustomHasteMap(options); } const hasteMap = new HasteMap(options); await hasteMap.setupCachePath(options); return hasteMap; }
type Options = { nodeComplete: (suite: TreeNode) => void; nodeStart: (suite: TreeNode) => void; queueRunnerFactory: any; runnableIds: Array<string>; tree: TreeNode; };
1,574
static async create(options: Options): Promise<IHasteMap> { if (options.hasteMapModulePath) { const CustomHasteMap = require(options.hasteMapModulePath); return new CustomHasteMap(options); } const hasteMap = new HasteMap(options); await hasteMap.setupCachePath(options); return hasteMap; }
type Options = { lastCommit?: boolean; withAncestor?: boolean; changedSince?: string; includePaths?: Array<string>; };
1,575
static async create(options: Options): Promise<IHasteMap> { if (options.hasteMapModulePath) { const CustomHasteMap = require(options.hasteMapModulePath); return new CustomHasteMap(options); } const hasteMap = new HasteMap(options); await hasteMap.setupCachePath(options); return hasteMap; }
type Options = { cacheDirectory?: string; computeDependencies?: boolean; computeSha1?: boolean; console?: Console; dependencyExtractor?: string | null; enableSymlinks?: boolean; extensions: Array<string>; forceNodeFilesystemAPI?: boolean; hasteImplModulePath?: string; hasteMapModulePath?: string; id: string; ignorePattern?: HasteRegExp; maxWorkers: number; mocksPattern?: string; platforms: Array<string>; resetCache?: boolean; retainAllFiles: boolean; rootDir: string; roots: Array<string>; skipPackageJson?: boolean; throwOnModuleCollision?: boolean; useWatchman?: boolean; watch?: boolean; };
1,576
static async create(options: Options): Promise<IHasteMap> { if (options.hasteMapModulePath) { const CustomHasteMap = require(options.hasteMapModulePath); return new CustomHasteMap(options); } const hasteMap = new HasteMap(options); await hasteMap.setupCachePath(options); return hasteMap; }
interface Options extends Omit<RequiredOptions, 'compareKeys' | 'theme'> { compareKeys: CompareKeys; theme: Required<RequiredOptions['theme']>; }
1,577
private constructor(options: Options) { super(); this._options = { cacheDirectory: options.cacheDirectory || tmpdir(), computeDependencies: options.computeDependencies ?? true, computeSha1: options.computeSha1 || false, dependencyExtractor: options.dependencyExtractor || null, enableSymlinks: options.enableSymlinks || false, extensions: options.extensions, forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, hasteImplModulePath: options.hasteImplModulePath, id: options.id, maxWorkers: options.maxWorkers, mocksPattern: options.mocksPattern ? new RegExp(options.mocksPattern) : null, platforms: options.platforms, resetCache: options.resetCache, retainAllFiles: options.retainAllFiles, rootDir: options.rootDir, roots: Array.from(new Set(options.roots)), skipPackageJson: !!options.skipPackageJson, throwOnModuleCollision: !!options.throwOnModuleCollision, useWatchman: options.useWatchman ?? true, watch: !!options.watch, }; this._console = options.console || globalThis.console; if (options.ignorePattern) { if (options.ignorePattern instanceof RegExp) { this._options.ignorePattern = new RegExp( options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), options.ignorePattern.flags, ); } else { throw new Error( 'jest-haste-map: the `ignorePattern` option must be a RegExp', ); } } else { this._options.ignorePattern = new RegExp(VCS_DIRECTORIES); } if (this._options.enableSymlinks && this._options.useWatchman) { throw new Error( 'jest-haste-map: enableSymlinks config option was set, but ' + 'is incompatible with watchman.\n' + 'Set either `enableSymlinks` to false or `useWatchman` to false.', ); } }
interface Options extends ShouldInstrumentOptions, CallerTransformOptions { isInternalModule?: boolean; }
1,578
private constructor(options: Options) { super(); this._options = { cacheDirectory: options.cacheDirectory || tmpdir(), computeDependencies: options.computeDependencies ?? true, computeSha1: options.computeSha1 || false, dependencyExtractor: options.dependencyExtractor || null, enableSymlinks: options.enableSymlinks || false, extensions: options.extensions, forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, hasteImplModulePath: options.hasteImplModulePath, id: options.id, maxWorkers: options.maxWorkers, mocksPattern: options.mocksPattern ? new RegExp(options.mocksPattern) : null, platforms: options.platforms, resetCache: options.resetCache, retainAllFiles: options.retainAllFiles, rootDir: options.rootDir, roots: Array.from(new Set(options.roots)), skipPackageJson: !!options.skipPackageJson, throwOnModuleCollision: !!options.throwOnModuleCollision, useWatchman: options.useWatchman ?? true, watch: !!options.watch, }; this._console = options.console || globalThis.console; if (options.ignorePattern) { if (options.ignorePattern instanceof RegExp) { this._options.ignorePattern = new RegExp( options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), options.ignorePattern.flags, ); } else { throw new Error( 'jest-haste-map: the `ignorePattern` option must be a RegExp', ); } } else { this._options.ignorePattern = new RegExp(VCS_DIRECTORIES); } if (this._options.enableSymlinks && this._options.useWatchman) { throw new Error( 'jest-haste-map: enableSymlinks config option was set, but ' + 'is incompatible with watchman.\n' + 'Set either `enableSymlinks` to false or `useWatchman` to false.', ); } }
type Options = { clearTimeout: (typeof globalThis)['clearTimeout']; fail: (error: Error) => void; onException: (error: Error) => void; queueableFns: Array<QueueableFn>; setTimeout: (typeof globalThis)['setTimeout']; userContext: unknown; };
1,579
private constructor(options: Options) { super(); this._options = { cacheDirectory: options.cacheDirectory || tmpdir(), computeDependencies: options.computeDependencies ?? true, computeSha1: options.computeSha1 || false, dependencyExtractor: options.dependencyExtractor || null, enableSymlinks: options.enableSymlinks || false, extensions: options.extensions, forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, hasteImplModulePath: options.hasteImplModulePath, id: options.id, maxWorkers: options.maxWorkers, mocksPattern: options.mocksPattern ? new RegExp(options.mocksPattern) : null, platforms: options.platforms, resetCache: options.resetCache, retainAllFiles: options.retainAllFiles, rootDir: options.rootDir, roots: Array.from(new Set(options.roots)), skipPackageJson: !!options.skipPackageJson, throwOnModuleCollision: !!options.throwOnModuleCollision, useWatchman: options.useWatchman ?? true, watch: !!options.watch, }; this._console = options.console || globalThis.console; if (options.ignorePattern) { if (options.ignorePattern instanceof RegExp) { this._options.ignorePattern = new RegExp( options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), options.ignorePattern.flags, ); } else { throw new Error( 'jest-haste-map: the `ignorePattern` option must be a RegExp', ); } } else { this._options.ignorePattern = new RegExp(VCS_DIRECTORIES); } if (this._options.enableSymlinks && this._options.useWatchman) { throw new Error( 'jest-haste-map: enableSymlinks config option was set, but ' + 'is incompatible with watchman.\n' + 'Set either `enableSymlinks` to false or `useWatchman` to false.', ); } }
type Options = { matcherName: string; passed: boolean; actual?: any; error?: any; expected?: any; message?: string | null; };
1,580
private constructor(options: Options) { super(); this._options = { cacheDirectory: options.cacheDirectory || tmpdir(), computeDependencies: options.computeDependencies ?? true, computeSha1: options.computeSha1 || false, dependencyExtractor: options.dependencyExtractor || null, enableSymlinks: options.enableSymlinks || false, extensions: options.extensions, forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, hasteImplModulePath: options.hasteImplModulePath, id: options.id, maxWorkers: options.maxWorkers, mocksPattern: options.mocksPattern ? new RegExp(options.mocksPattern) : null, platforms: options.platforms, resetCache: options.resetCache, retainAllFiles: options.retainAllFiles, rootDir: options.rootDir, roots: Array.from(new Set(options.roots)), skipPackageJson: !!options.skipPackageJson, throwOnModuleCollision: !!options.throwOnModuleCollision, useWatchman: options.useWatchman ?? true, watch: !!options.watch, }; this._console = options.console || globalThis.console; if (options.ignorePattern) { if (options.ignorePattern instanceof RegExp) { this._options.ignorePattern = new RegExp( options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), options.ignorePattern.flags, ); } else { throw new Error( 'jest-haste-map: the `ignorePattern` option must be a RegExp', ); } } else { this._options.ignorePattern = new RegExp(VCS_DIRECTORIES); } if (this._options.enableSymlinks && this._options.useWatchman) { throw new Error( 'jest-haste-map: enableSymlinks config option was set, but ' + 'is incompatible with watchman.\n' + 'Set either `enableSymlinks` to false or `useWatchman` to false.', ); } }
type Options = { nodeComplete: (suite: TreeNode) => void; nodeStart: (suite: TreeNode) => void; queueRunnerFactory: any; runnableIds: Array<string>; tree: TreeNode; };
1,581
private constructor(options: Options) { super(); this._options = { cacheDirectory: options.cacheDirectory || tmpdir(), computeDependencies: options.computeDependencies ?? true, computeSha1: options.computeSha1 || false, dependencyExtractor: options.dependencyExtractor || null, enableSymlinks: options.enableSymlinks || false, extensions: options.extensions, forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, hasteImplModulePath: options.hasteImplModulePath, id: options.id, maxWorkers: options.maxWorkers, mocksPattern: options.mocksPattern ? new RegExp(options.mocksPattern) : null, platforms: options.platforms, resetCache: options.resetCache, retainAllFiles: options.retainAllFiles, rootDir: options.rootDir, roots: Array.from(new Set(options.roots)), skipPackageJson: !!options.skipPackageJson, throwOnModuleCollision: !!options.throwOnModuleCollision, useWatchman: options.useWatchman ?? true, watch: !!options.watch, }; this._console = options.console || globalThis.console; if (options.ignorePattern) { if (options.ignorePattern instanceof RegExp) { this._options.ignorePattern = new RegExp( options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), options.ignorePattern.flags, ); } else { throw new Error( 'jest-haste-map: the `ignorePattern` option must be a RegExp', ); } } else { this._options.ignorePattern = new RegExp(VCS_DIRECTORIES); } if (this._options.enableSymlinks && this._options.useWatchman) { throw new Error( 'jest-haste-map: enableSymlinks config option was set, but ' + 'is incompatible with watchman.\n' + 'Set either `enableSymlinks` to false or `useWatchman` to false.', ); } }
type Options = { lastCommit?: boolean; withAncestor?: boolean; changedSince?: string; includePaths?: Array<string>; };
1,582
private constructor(options: Options) { super(); this._options = { cacheDirectory: options.cacheDirectory || tmpdir(), computeDependencies: options.computeDependencies ?? true, computeSha1: options.computeSha1 || false, dependencyExtractor: options.dependencyExtractor || null, enableSymlinks: options.enableSymlinks || false, extensions: options.extensions, forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, hasteImplModulePath: options.hasteImplModulePath, id: options.id, maxWorkers: options.maxWorkers, mocksPattern: options.mocksPattern ? new RegExp(options.mocksPattern) : null, platforms: options.platforms, resetCache: options.resetCache, retainAllFiles: options.retainAllFiles, rootDir: options.rootDir, roots: Array.from(new Set(options.roots)), skipPackageJson: !!options.skipPackageJson, throwOnModuleCollision: !!options.throwOnModuleCollision, useWatchman: options.useWatchman ?? true, watch: !!options.watch, }; this._console = options.console || globalThis.console; if (options.ignorePattern) { if (options.ignorePattern instanceof RegExp) { this._options.ignorePattern = new RegExp( options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), options.ignorePattern.flags, ); } else { throw new Error( 'jest-haste-map: the `ignorePattern` option must be a RegExp', ); } } else { this._options.ignorePattern = new RegExp(VCS_DIRECTORIES); } if (this._options.enableSymlinks && this._options.useWatchman) { throw new Error( 'jest-haste-map: enableSymlinks config option was set, but ' + 'is incompatible with watchman.\n' + 'Set either `enableSymlinks` to false or `useWatchman` to false.', ); } }
type Options = { cacheDirectory?: string; computeDependencies?: boolean; computeSha1?: boolean; console?: Console; dependencyExtractor?: string | null; enableSymlinks?: boolean; extensions: Array<string>; forceNodeFilesystemAPI?: boolean; hasteImplModulePath?: string; hasteMapModulePath?: string; id: string; ignorePattern?: HasteRegExp; maxWorkers: number; mocksPattern?: string; platforms: Array<string>; resetCache?: boolean; retainAllFiles: boolean; rootDir: string; roots: Array<string>; skipPackageJson?: boolean; throwOnModuleCollision?: boolean; useWatchman?: boolean; watch?: boolean; };
1,583
private constructor(options: Options) { super(); this._options = { cacheDirectory: options.cacheDirectory || tmpdir(), computeDependencies: options.computeDependencies ?? true, computeSha1: options.computeSha1 || false, dependencyExtractor: options.dependencyExtractor || null, enableSymlinks: options.enableSymlinks || false, extensions: options.extensions, forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, hasteImplModulePath: options.hasteImplModulePath, id: options.id, maxWorkers: options.maxWorkers, mocksPattern: options.mocksPattern ? new RegExp(options.mocksPattern) : null, platforms: options.platforms, resetCache: options.resetCache, retainAllFiles: options.retainAllFiles, rootDir: options.rootDir, roots: Array.from(new Set(options.roots)), skipPackageJson: !!options.skipPackageJson, throwOnModuleCollision: !!options.throwOnModuleCollision, useWatchman: options.useWatchman ?? true, watch: !!options.watch, }; this._console = options.console || globalThis.console; if (options.ignorePattern) { if (options.ignorePattern instanceof RegExp) { this._options.ignorePattern = new RegExp( options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), options.ignorePattern.flags, ); } else { throw new Error( 'jest-haste-map: the `ignorePattern` option must be a RegExp', ); } } else { this._options.ignorePattern = new RegExp(VCS_DIRECTORIES); } if (this._options.enableSymlinks && this._options.useWatchman) { throw new Error( 'jest-haste-map: enableSymlinks config option was set, but ' + 'is incompatible with watchman.\n' + 'Set either `enableSymlinks` to false or `useWatchman` to false.', ); } }
interface Options extends Omit<RequiredOptions, 'compareKeys' | 'theme'> { compareKeys: CompareKeys; theme: Required<RequiredOptions['theme']>; }
1,584
private async setupCachePath(options: Options): Promise<void> { const rootDirHash = createHash('sha1') .update(options.rootDir) .digest('hex') .substring(0, 32); let hasteImplHash = ''; let dependencyExtractorHash = ''; if (options.hasteImplModulePath) { const hasteImpl = require(options.hasteImplModulePath); if (hasteImpl.getCacheKey) { hasteImplHash = String(hasteImpl.getCacheKey()); } } if (options.dependencyExtractor) { const dependencyExtractor = await requireOrImportModule<DependencyExtractor>( options.dependencyExtractor, false, ); if (dependencyExtractor.getCacheKey) { dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); } } this._cachePath = HasteMap.getCacheFilePath( this._options.cacheDirectory, `haste-map-${this._options.id}-${rootDirHash}`, VERSION, this._options.id, this._options.roots .map(root => fastPath.relative(options.rootDir, root)) .join(':'), this._options.extensions.join(':'), this._options.platforms.join(':'), this._options.computeSha1.toString(), options.mocksPattern || '', (options.ignorePattern || '').toString(), hasteImplHash, dependencyExtractorHash, this._options.computeDependencies.toString(), ); }
interface Options extends ShouldInstrumentOptions, CallerTransformOptions { isInternalModule?: boolean; }
1,585
private async setupCachePath(options: Options): Promise<void> { const rootDirHash = createHash('sha1') .update(options.rootDir) .digest('hex') .substring(0, 32); let hasteImplHash = ''; let dependencyExtractorHash = ''; if (options.hasteImplModulePath) { const hasteImpl = require(options.hasteImplModulePath); if (hasteImpl.getCacheKey) { hasteImplHash = String(hasteImpl.getCacheKey()); } } if (options.dependencyExtractor) { const dependencyExtractor = await requireOrImportModule<DependencyExtractor>( options.dependencyExtractor, false, ); if (dependencyExtractor.getCacheKey) { dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); } } this._cachePath = HasteMap.getCacheFilePath( this._options.cacheDirectory, `haste-map-${this._options.id}-${rootDirHash}`, VERSION, this._options.id, this._options.roots .map(root => fastPath.relative(options.rootDir, root)) .join(':'), this._options.extensions.join(':'), this._options.platforms.join(':'), this._options.computeSha1.toString(), options.mocksPattern || '', (options.ignorePattern || '').toString(), hasteImplHash, dependencyExtractorHash, this._options.computeDependencies.toString(), ); }
type Options = { clearTimeout: (typeof globalThis)['clearTimeout']; fail: (error: Error) => void; onException: (error: Error) => void; queueableFns: Array<QueueableFn>; setTimeout: (typeof globalThis)['setTimeout']; userContext: unknown; };
1,586
private async setupCachePath(options: Options): Promise<void> { const rootDirHash = createHash('sha1') .update(options.rootDir) .digest('hex') .substring(0, 32); let hasteImplHash = ''; let dependencyExtractorHash = ''; if (options.hasteImplModulePath) { const hasteImpl = require(options.hasteImplModulePath); if (hasteImpl.getCacheKey) { hasteImplHash = String(hasteImpl.getCacheKey()); } } if (options.dependencyExtractor) { const dependencyExtractor = await requireOrImportModule<DependencyExtractor>( options.dependencyExtractor, false, ); if (dependencyExtractor.getCacheKey) { dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); } } this._cachePath = HasteMap.getCacheFilePath( this._options.cacheDirectory, `haste-map-${this._options.id}-${rootDirHash}`, VERSION, this._options.id, this._options.roots .map(root => fastPath.relative(options.rootDir, root)) .join(':'), this._options.extensions.join(':'), this._options.platforms.join(':'), this._options.computeSha1.toString(), options.mocksPattern || '', (options.ignorePattern || '').toString(), hasteImplHash, dependencyExtractorHash, this._options.computeDependencies.toString(), ); }
type Options = { matcherName: string; passed: boolean; actual?: any; error?: any; expected?: any; message?: string | null; };
1,587
private async setupCachePath(options: Options): Promise<void> { const rootDirHash = createHash('sha1') .update(options.rootDir) .digest('hex') .substring(0, 32); let hasteImplHash = ''; let dependencyExtractorHash = ''; if (options.hasteImplModulePath) { const hasteImpl = require(options.hasteImplModulePath); if (hasteImpl.getCacheKey) { hasteImplHash = String(hasteImpl.getCacheKey()); } } if (options.dependencyExtractor) { const dependencyExtractor = await requireOrImportModule<DependencyExtractor>( options.dependencyExtractor, false, ); if (dependencyExtractor.getCacheKey) { dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); } } this._cachePath = HasteMap.getCacheFilePath( this._options.cacheDirectory, `haste-map-${this._options.id}-${rootDirHash}`, VERSION, this._options.id, this._options.roots .map(root => fastPath.relative(options.rootDir, root)) .join(':'), this._options.extensions.join(':'), this._options.platforms.join(':'), this._options.computeSha1.toString(), options.mocksPattern || '', (options.ignorePattern || '').toString(), hasteImplHash, dependencyExtractorHash, this._options.computeDependencies.toString(), ); }
type Options = { nodeComplete: (suite: TreeNode) => void; nodeStart: (suite: TreeNode) => void; queueRunnerFactory: any; runnableIds: Array<string>; tree: TreeNode; };
1,588
private async setupCachePath(options: Options): Promise<void> { const rootDirHash = createHash('sha1') .update(options.rootDir) .digest('hex') .substring(0, 32); let hasteImplHash = ''; let dependencyExtractorHash = ''; if (options.hasteImplModulePath) { const hasteImpl = require(options.hasteImplModulePath); if (hasteImpl.getCacheKey) { hasteImplHash = String(hasteImpl.getCacheKey()); } } if (options.dependencyExtractor) { const dependencyExtractor = await requireOrImportModule<DependencyExtractor>( options.dependencyExtractor, false, ); if (dependencyExtractor.getCacheKey) { dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); } } this._cachePath = HasteMap.getCacheFilePath( this._options.cacheDirectory, `haste-map-${this._options.id}-${rootDirHash}`, VERSION, this._options.id, this._options.roots .map(root => fastPath.relative(options.rootDir, root)) .join(':'), this._options.extensions.join(':'), this._options.platforms.join(':'), this._options.computeSha1.toString(), options.mocksPattern || '', (options.ignorePattern || '').toString(), hasteImplHash, dependencyExtractorHash, this._options.computeDependencies.toString(), ); }
type Options = { lastCommit?: boolean; withAncestor?: boolean; changedSince?: string; includePaths?: Array<string>; };
1,589
private async setupCachePath(options: Options): Promise<void> { const rootDirHash = createHash('sha1') .update(options.rootDir) .digest('hex') .substring(0, 32); let hasteImplHash = ''; let dependencyExtractorHash = ''; if (options.hasteImplModulePath) { const hasteImpl = require(options.hasteImplModulePath); if (hasteImpl.getCacheKey) { hasteImplHash = String(hasteImpl.getCacheKey()); } } if (options.dependencyExtractor) { const dependencyExtractor = await requireOrImportModule<DependencyExtractor>( options.dependencyExtractor, false, ); if (dependencyExtractor.getCacheKey) { dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); } } this._cachePath = HasteMap.getCacheFilePath( this._options.cacheDirectory, `haste-map-${this._options.id}-${rootDirHash}`, VERSION, this._options.id, this._options.roots .map(root => fastPath.relative(options.rootDir, root)) .join(':'), this._options.extensions.join(':'), this._options.platforms.join(':'), this._options.computeSha1.toString(), options.mocksPattern || '', (options.ignorePattern || '').toString(), hasteImplHash, dependencyExtractorHash, this._options.computeDependencies.toString(), ); }
type Options = { cacheDirectory?: string; computeDependencies?: boolean; computeSha1?: boolean; console?: Console; dependencyExtractor?: string | null; enableSymlinks?: boolean; extensions: Array<string>; forceNodeFilesystemAPI?: boolean; hasteImplModulePath?: string; hasteMapModulePath?: string; id: string; ignorePattern?: HasteRegExp; maxWorkers: number; mocksPattern?: string; platforms: Array<string>; resetCache?: boolean; retainAllFiles: boolean; rootDir: string; roots: Array<string>; skipPackageJson?: boolean; throwOnModuleCollision?: boolean; useWatchman?: boolean; watch?: boolean; };
1,590
private async setupCachePath(options: Options): Promise<void> { const rootDirHash = createHash('sha1') .update(options.rootDir) .digest('hex') .substring(0, 32); let hasteImplHash = ''; let dependencyExtractorHash = ''; if (options.hasteImplModulePath) { const hasteImpl = require(options.hasteImplModulePath); if (hasteImpl.getCacheKey) { hasteImplHash = String(hasteImpl.getCacheKey()); } } if (options.dependencyExtractor) { const dependencyExtractor = await requireOrImportModule<DependencyExtractor>( options.dependencyExtractor, false, ); if (dependencyExtractor.getCacheKey) { dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); } } this._cachePath = HasteMap.getCacheFilePath( this._options.cacheDirectory, `haste-map-${this._options.id}-${rootDirHash}`, VERSION, this._options.id, this._options.roots .map(root => fastPath.relative(options.rootDir, root)) .join(':'), this._options.extensions.join(':'), this._options.platforms.join(':'), this._options.computeSha1.toString(), options.mocksPattern || '', (options.ignorePattern || '').toString(), hasteImplHash, dependencyExtractorHash, this._options.computeDependencies.toString(), ); }
interface Options extends Omit<RequiredOptions, 'compareKeys' | 'theme'> { compareKeys: CompareKeys; theme: Required<RequiredOptions['theme']>; }
1,591
static getModuleMapFromJSON(json: SerializableModuleMap): HasteModuleMap { return HasteModuleMap.fromJSON(json); }
type SerializableModuleMap = { duplicates: ReadonlyArray<[string, [string, [string, [string, number]]]]>; map: ReadonlyArray<[string, ValueType<ModuleMapData>]>; mocks: ReadonlyArray<[string, ValueType<MockData>]>; rootDir: string; };
1,592
private _processFile( hasteMap: InternalHasteMap, map: ModuleMapData, mocks: MockData, filePath: string, workerOptions?: {forceInBand: boolean}, ): Promise<void> | null { const rootDir = this._options.rootDir; const setModule = (id: string, module: ModuleMetaData) => { let moduleMap = map.get(id); if (!moduleMap) { moduleMap = Object.create(null) as ModuleMapItem; map.set(id, moduleMap); } const platform = getPlatformExtension(module[H.PATH], this._options.platforms) || H.GENERIC_PLATFORM; const existingModule = moduleMap[platform]; if (existingModule && existingModule[H.PATH] !== module[H.PATH]) { const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; this._console[method]( [ `jest-haste-map: Haste module naming collision: ${id}`, ' The following files share their name; please adjust your hasteImpl:', ` * <rootDir>${path.sep}${existingModule[H.PATH]}`, ` * <rootDir>${path.sep}${module[H.PATH]}`, '', ].join('\n'), ); if (this._options.throwOnModuleCollision) { throw new DuplicateError(existingModule[H.PATH], module[H.PATH]); } // We do NOT want consumers to use a module that is ambiguous. delete moduleMap[platform]; if (Object.keys(moduleMap).length === 1) { map.delete(id); } let dupsByPlatform = hasteMap.duplicates.get(id); if (dupsByPlatform == null) { dupsByPlatform = new Map(); hasteMap.duplicates.set(id, dupsByPlatform); } const dups = new Map([ [module[H.PATH], module[H.TYPE]], [existingModule[H.PATH], existingModule[H.TYPE]], ]); dupsByPlatform.set(platform, dups); return; } const dupsByPlatform = hasteMap.duplicates.get(id); if (dupsByPlatform != null) { const dups = dupsByPlatform.get(platform); if (dups != null) { dups.set(module[H.PATH], module[H.TYPE]); } return; } moduleMap[platform] = module; }; const relativeFilePath = fastPath.relative(rootDir, filePath); const fileMetadata = hasteMap.files.get(relativeFilePath); if (!fileMetadata) { throw new Error( 'jest-haste-map: File to process was not found in the haste map.', ); } const moduleMetadata = hasteMap.map.get(fileMetadata[H.ID]); const computeSha1 = this._options.computeSha1 && !fileMetadata[H.SHA1]; // Callback called when the response from the worker is successful. const workerReply = (metadata: WorkerMetadata) => { // `1` for truthy values instead of `true` to save cache space. fileMetadata[H.VISITED] = 1; const metadataId = metadata.id; const metadataModule = metadata.module; if (metadataId && metadataModule) { fileMetadata[H.ID] = metadataId; setModule(metadataId, metadataModule); } fileMetadata[H.DEPENDENCIES] = metadata.dependencies ? metadata.dependencies.join(H.DEPENDENCY_DELIM) : ''; if (computeSha1) { fileMetadata[H.SHA1] = metadata.sha1; } }; // Callback called when the response from the worker is an error. const workerError = (error: Error | any) => { if (typeof error !== 'object' || !error.message || !error.stack) { error = new Error(error); error.stack = ''; // Remove stack for stack-less errors. } if (!['ENOENT', 'EACCES'].includes(error.code)) { throw error; } // If a file cannot be read we remove it from the file list and // ignore the failure silently. hasteMap.files.delete(relativeFilePath); }; // If we retain all files in the virtual HasteFS representation, we avoid // reading them if they aren't important (node_modules). if (this._options.retainAllFiles && filePath.includes(NODE_MODULES)) { if (computeSha1) { return this._getWorker(workerOptions) .getSha1({ computeDependencies: this._options.computeDependencies, computeSha1, dependencyExtractor: this._options.dependencyExtractor, filePath, hasteImplModulePath: this._options.hasteImplModulePath, rootDir, }) .then(workerReply, workerError); } return null; } if ( this._options.mocksPattern && this._options.mocksPattern.test(filePath) ) { const mockPath = getMockName(filePath); const existingMockPath = mocks.get(mockPath); if (existingMockPath) { const secondMockPath = fastPath.relative(rootDir, filePath); if (existingMockPath !== secondMockPath) { const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; this._console[method]( [ `jest-haste-map: duplicate manual mock found: ${mockPath}`, ' The following files share their name; please delete one of them:', ` * <rootDir>${path.sep}${existingMockPath}`, ` * <rootDir>${path.sep}${secondMockPath}`, '', ].join('\n'), ); if (this._options.throwOnModuleCollision) { throw new DuplicateError(existingMockPath, secondMockPath); } } } mocks.set(mockPath, relativeFilePath); } if (fileMetadata[H.VISITED]) { if (!fileMetadata[H.ID]) { return null; } if (moduleMetadata != null) { const platform = getPlatformExtension(filePath, this._options.platforms) || H.GENERIC_PLATFORM; const module = moduleMetadata[platform]; if (module == null) { return null; } const moduleId = fileMetadata[H.ID]; let modulesByPlatform = map.get(moduleId); if (!modulesByPlatform) { modulesByPlatform = Object.create(null) as ModuleMapItem; map.set(moduleId, modulesByPlatform); } modulesByPlatform[platform] = module; return null; } } return this._getWorker(workerOptions) .worker({ computeDependencies: this._options.computeDependencies, computeSha1, dependencyExtractor: this._options.dependencyExtractor, filePath, hasteImplModulePath: this._options.hasteImplModulePath, rootDir, }) .then(workerReply, workerError); }
type MockData = Map<string, string>;
1,593
private _processFile( hasteMap: InternalHasteMap, map: ModuleMapData, mocks: MockData, filePath: string, workerOptions?: {forceInBand: boolean}, ): Promise<void> | null { const rootDir = this._options.rootDir; const setModule = (id: string, module: ModuleMetaData) => { let moduleMap = map.get(id); if (!moduleMap) { moduleMap = Object.create(null) as ModuleMapItem; map.set(id, moduleMap); } const platform = getPlatformExtension(module[H.PATH], this._options.platforms) || H.GENERIC_PLATFORM; const existingModule = moduleMap[platform]; if (existingModule && existingModule[H.PATH] !== module[H.PATH]) { const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; this._console[method]( [ `jest-haste-map: Haste module naming collision: ${id}`, ' The following files share their name; please adjust your hasteImpl:', ` * <rootDir>${path.sep}${existingModule[H.PATH]}`, ` * <rootDir>${path.sep}${module[H.PATH]}`, '', ].join('\n'), ); if (this._options.throwOnModuleCollision) { throw new DuplicateError(existingModule[H.PATH], module[H.PATH]); } // We do NOT want consumers to use a module that is ambiguous. delete moduleMap[platform]; if (Object.keys(moduleMap).length === 1) { map.delete(id); } let dupsByPlatform = hasteMap.duplicates.get(id); if (dupsByPlatform == null) { dupsByPlatform = new Map(); hasteMap.duplicates.set(id, dupsByPlatform); } const dups = new Map([ [module[H.PATH], module[H.TYPE]], [existingModule[H.PATH], existingModule[H.TYPE]], ]); dupsByPlatform.set(platform, dups); return; } const dupsByPlatform = hasteMap.duplicates.get(id); if (dupsByPlatform != null) { const dups = dupsByPlatform.get(platform); if (dups != null) { dups.set(module[H.PATH], module[H.TYPE]); } return; } moduleMap[platform] = module; }; const relativeFilePath = fastPath.relative(rootDir, filePath); const fileMetadata = hasteMap.files.get(relativeFilePath); if (!fileMetadata) { throw new Error( 'jest-haste-map: File to process was not found in the haste map.', ); } const moduleMetadata = hasteMap.map.get(fileMetadata[H.ID]); const computeSha1 = this._options.computeSha1 && !fileMetadata[H.SHA1]; // Callback called when the response from the worker is successful. const workerReply = (metadata: WorkerMetadata) => { // `1` for truthy values instead of `true` to save cache space. fileMetadata[H.VISITED] = 1; const metadataId = metadata.id; const metadataModule = metadata.module; if (metadataId && metadataModule) { fileMetadata[H.ID] = metadataId; setModule(metadataId, metadataModule); } fileMetadata[H.DEPENDENCIES] = metadata.dependencies ? metadata.dependencies.join(H.DEPENDENCY_DELIM) : ''; if (computeSha1) { fileMetadata[H.SHA1] = metadata.sha1; } }; // Callback called when the response from the worker is an error. const workerError = (error: Error | any) => { if (typeof error !== 'object' || !error.message || !error.stack) { error = new Error(error); error.stack = ''; // Remove stack for stack-less errors. } if (!['ENOENT', 'EACCES'].includes(error.code)) { throw error; } // If a file cannot be read we remove it from the file list and // ignore the failure silently. hasteMap.files.delete(relativeFilePath); }; // If we retain all files in the virtual HasteFS representation, we avoid // reading them if they aren't important (node_modules). if (this._options.retainAllFiles && filePath.includes(NODE_MODULES)) { if (computeSha1) { return this._getWorker(workerOptions) .getSha1({ computeDependencies: this._options.computeDependencies, computeSha1, dependencyExtractor: this._options.dependencyExtractor, filePath, hasteImplModulePath: this._options.hasteImplModulePath, rootDir, }) .then(workerReply, workerError); } return null; } if ( this._options.mocksPattern && this._options.mocksPattern.test(filePath) ) { const mockPath = getMockName(filePath); const existingMockPath = mocks.get(mockPath); if (existingMockPath) { const secondMockPath = fastPath.relative(rootDir, filePath); if (existingMockPath !== secondMockPath) { const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; this._console[method]( [ `jest-haste-map: duplicate manual mock found: ${mockPath}`, ' The following files share their name; please delete one of them:', ` * <rootDir>${path.sep}${existingMockPath}`, ` * <rootDir>${path.sep}${secondMockPath}`, '', ].join('\n'), ); if (this._options.throwOnModuleCollision) { throw new DuplicateError(existingMockPath, secondMockPath); } } } mocks.set(mockPath, relativeFilePath); } if (fileMetadata[H.VISITED]) { if (!fileMetadata[H.ID]) { return null; } if (moduleMetadata != null) { const platform = getPlatformExtension(filePath, this._options.platforms) || H.GENERIC_PLATFORM; const module = moduleMetadata[platform]; if (module == null) { return null; } const moduleId = fileMetadata[H.ID]; let modulesByPlatform = map.get(moduleId); if (!modulesByPlatform) { modulesByPlatform = Object.create(null) as ModuleMapItem; map.set(moduleId, modulesByPlatform); } modulesByPlatform[platform] = module; return null; } } return this._getWorker(workerOptions) .worker({ computeDependencies: this._options.computeDependencies, computeSha1, dependencyExtractor: this._options.dependencyExtractor, filePath, hasteImplModulePath: this._options.hasteImplModulePath, rootDir, }) .then(workerReply, workerError); }
type ModuleMapData = Map<string, ModuleMapItem>;
1,594
private _processFile( hasteMap: InternalHasteMap, map: ModuleMapData, mocks: MockData, filePath: string, workerOptions?: {forceInBand: boolean}, ): Promise<void> | null { const rootDir = this._options.rootDir; const setModule = (id: string, module: ModuleMetaData) => { let moduleMap = map.get(id); if (!moduleMap) { moduleMap = Object.create(null) as ModuleMapItem; map.set(id, moduleMap); } const platform = getPlatformExtension(module[H.PATH], this._options.platforms) || H.GENERIC_PLATFORM; const existingModule = moduleMap[platform]; if (existingModule && existingModule[H.PATH] !== module[H.PATH]) { const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; this._console[method]( [ `jest-haste-map: Haste module naming collision: ${id}`, ' The following files share their name; please adjust your hasteImpl:', ` * <rootDir>${path.sep}${existingModule[H.PATH]}`, ` * <rootDir>${path.sep}${module[H.PATH]}`, '', ].join('\n'), ); if (this._options.throwOnModuleCollision) { throw new DuplicateError(existingModule[H.PATH], module[H.PATH]); } // We do NOT want consumers to use a module that is ambiguous. delete moduleMap[platform]; if (Object.keys(moduleMap).length === 1) { map.delete(id); } let dupsByPlatform = hasteMap.duplicates.get(id); if (dupsByPlatform == null) { dupsByPlatform = new Map(); hasteMap.duplicates.set(id, dupsByPlatform); } const dups = new Map([ [module[H.PATH], module[H.TYPE]], [existingModule[H.PATH], existingModule[H.TYPE]], ]); dupsByPlatform.set(platform, dups); return; } const dupsByPlatform = hasteMap.duplicates.get(id); if (dupsByPlatform != null) { const dups = dupsByPlatform.get(platform); if (dups != null) { dups.set(module[H.PATH], module[H.TYPE]); } return; } moduleMap[platform] = module; }; const relativeFilePath = fastPath.relative(rootDir, filePath); const fileMetadata = hasteMap.files.get(relativeFilePath); if (!fileMetadata) { throw new Error( 'jest-haste-map: File to process was not found in the haste map.', ); } const moduleMetadata = hasteMap.map.get(fileMetadata[H.ID]); const computeSha1 = this._options.computeSha1 && !fileMetadata[H.SHA1]; // Callback called when the response from the worker is successful. const workerReply = (metadata: WorkerMetadata) => { // `1` for truthy values instead of `true` to save cache space. fileMetadata[H.VISITED] = 1; const metadataId = metadata.id; const metadataModule = metadata.module; if (metadataId && metadataModule) { fileMetadata[H.ID] = metadataId; setModule(metadataId, metadataModule); } fileMetadata[H.DEPENDENCIES] = metadata.dependencies ? metadata.dependencies.join(H.DEPENDENCY_DELIM) : ''; if (computeSha1) { fileMetadata[H.SHA1] = metadata.sha1; } }; // Callback called when the response from the worker is an error. const workerError = (error: Error | any) => { if (typeof error !== 'object' || !error.message || !error.stack) { error = new Error(error); error.stack = ''; // Remove stack for stack-less errors. } if (!['ENOENT', 'EACCES'].includes(error.code)) { throw error; } // If a file cannot be read we remove it from the file list and // ignore the failure silently. hasteMap.files.delete(relativeFilePath); }; // If we retain all files in the virtual HasteFS representation, we avoid // reading them if they aren't important (node_modules). if (this._options.retainAllFiles && filePath.includes(NODE_MODULES)) { if (computeSha1) { return this._getWorker(workerOptions) .getSha1({ computeDependencies: this._options.computeDependencies, computeSha1, dependencyExtractor: this._options.dependencyExtractor, filePath, hasteImplModulePath: this._options.hasteImplModulePath, rootDir, }) .then(workerReply, workerError); } return null; } if ( this._options.mocksPattern && this._options.mocksPattern.test(filePath) ) { const mockPath = getMockName(filePath); const existingMockPath = mocks.get(mockPath); if (existingMockPath) { const secondMockPath = fastPath.relative(rootDir, filePath); if (existingMockPath !== secondMockPath) { const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; this._console[method]( [ `jest-haste-map: duplicate manual mock found: ${mockPath}`, ' The following files share their name; please delete one of them:', ` * <rootDir>${path.sep}${existingMockPath}`, ` * <rootDir>${path.sep}${secondMockPath}`, '', ].join('\n'), ); if (this._options.throwOnModuleCollision) { throw new DuplicateError(existingMockPath, secondMockPath); } } } mocks.set(mockPath, relativeFilePath); } if (fileMetadata[H.VISITED]) { if (!fileMetadata[H.ID]) { return null; } if (moduleMetadata != null) { const platform = getPlatformExtension(filePath, this._options.platforms) || H.GENERIC_PLATFORM; const module = moduleMetadata[platform]; if (module == null) { return null; } const moduleId = fileMetadata[H.ID]; let modulesByPlatform = map.get(moduleId); if (!modulesByPlatform) { modulesByPlatform = Object.create(null) as ModuleMapItem; map.set(moduleId, modulesByPlatform); } modulesByPlatform[platform] = module; return null; } } return this._getWorker(workerOptions) .worker({ computeDependencies: this._options.computeDependencies, computeSha1, dependencyExtractor: this._options.dependencyExtractor, filePath, hasteImplModulePath: this._options.hasteImplModulePath, rootDir, }) .then(workerReply, workerError); }
type InternalHasteMap = { clocks: WatchmanClocks; duplicates: DuplicatesIndex; files: FileData; map: ModuleMapData; mocks: MockData; };
1,595
(metadata: WorkerMetadata) => { // `1` for truthy values instead of `true` to save cache space. fileMetadata[H.VISITED] = 1; const metadataId = metadata.id; const metadataModule = metadata.module; if (metadataId && metadataModule) { fileMetadata[H.ID] = metadataId; setModule(metadataId, metadataModule); } fileMetadata[H.DEPENDENCIES] = metadata.dependencies ? metadata.dependencies.join(H.DEPENDENCY_DELIM) : ''; if (computeSha1) { fileMetadata[H.SHA1] = metadata.sha1; } }
type WorkerMetadata = { dependencies: Array<string> | undefined | null; id: string | undefined | null; module: ModuleMetaData | undefined | null; sha1: string | undefined | null; };
1,596
private _persist(hasteMap: InternalHasteMap) { writeFileSync(this._cachePath, serialize(hasteMap)); }
type InternalHasteMap = { clocks: WatchmanClocks; duplicates: DuplicatesIndex; files: FileData; map: ModuleMapData; mocks: MockData; };
1,597
private async _crawl(hasteMap: InternalHasteMap) { const options = this._options; const ignore = this._ignore.bind(this); const crawl = (await this._shouldUseWatchman()) ? watchmanCrawl : nodeCrawl; const crawlerOptions: CrawlerOptions = { computeSha1: options.computeSha1, data: hasteMap, enableSymlinks: options.enableSymlinks, extensions: options.extensions, forceNodeFilesystemAPI: options.forceNodeFilesystemAPI, ignore, rootDir: options.rootDir, roots: options.roots, }; const retry = (error: Error) => { if (crawl === watchmanCrawl) { this._console.warn( 'jest-haste-map: Watchman crawl failed. Retrying once with node ' + 'crawler.\n' + " Usually this happens when watchman isn't running. Create an " + "empty `.watchmanconfig` file in your project's root folder or " + 'initialize a git or hg repository in your project.\n' + ` ${error}`, ); return nodeCrawl(crawlerOptions).catch(e => { throw new Error( 'Crawler retry failed:\n' + ` Original error: ${error.message}\n` + ` Retry error: ${e.message}\n`, ); }); } throw error; }; try { return await crawl(crawlerOptions); } catch (error: any) { return retry(error); } }
type InternalHasteMap = { clocks: WatchmanClocks; duplicates: DuplicatesIndex; files: FileData; map: ModuleMapData; mocks: MockData; };
1,598
private async _watch(hasteMap: InternalHasteMap): Promise<void> { if (!this._options.watch) { return Promise.resolve(); } // In watch mode, we'll only warn about module collisions and we'll retain // all files, even changes to node_modules. this._options.throwOnModuleCollision = false; this._options.retainAllFiles = true; // WatchmanWatcher > FSEventsWatcher > sane.NodeWatcher const Watcher = (await this._shouldUseWatchman()) ? WatchmanWatcher : FSEventsWatcher.isSupported() ? FSEventsWatcher : NodeWatcher; const extensions = this._options.extensions; const ignorePattern = this._options.ignorePattern; const rootDir = this._options.rootDir; let changeQueue: Promise<null | void> = Promise.resolve(); let eventsQueue: EventsQueue = []; // We only need to copy the entire haste map once on every "frame". let mustCopy = true; const createWatcher = (root: string): Promise<Watcher> => { const watcher = new Watcher(root, { dot: true, glob: extensions.map(extension => `**/*.${extension}`), ignored: ignorePattern, }); return new Promise((resolve, reject) => { const rejectTimeout = setTimeout( () => reject(new Error('Failed to start watch mode.')), MAX_WAIT_TIME, ); watcher.once('ready', () => { clearTimeout(rejectTimeout); watcher.on('all', onChange); resolve(watcher); }); }); }; const emitChange = () => { if (eventsQueue.length) { mustCopy = true; const changeEvent: ChangeEvent = { eventsQueue, hasteFS: new HasteFS({files: hasteMap.files, rootDir}), moduleMap: new HasteModuleMap({ duplicates: hasteMap.duplicates, map: hasteMap.map, mocks: hasteMap.mocks, rootDir, }), }; this.emit('change', changeEvent); eventsQueue = []; } }; const onChange = ( type: string, filePath: string, root: string, stat?: Stats, ) => { filePath = path.join(root, normalizePathSep(filePath)); if ( (stat && stat.isDirectory()) || this._ignore(filePath) || !extensions.some(extension => filePath.endsWith(extension)) ) { return; } const relativeFilePath = fastPath.relative(rootDir, filePath); const fileMetadata = hasteMap.files.get(relativeFilePath); // The file has been accessed, not modified if ( type === 'change' && fileMetadata && stat && fileMetadata[H.MTIME] === stat.mtime.getTime() ) { return; } changeQueue = changeQueue .then(() => { // If we get duplicate events for the same file, ignore them. if ( eventsQueue.find( event => event.type === type && event.filePath === filePath && ((!event.stat && !stat) || (!!event.stat && !!stat && event.stat.mtime.getTime() === stat.mtime.getTime())), ) ) { return null; } if (mustCopy) { mustCopy = false; hasteMap = { clocks: new Map(hasteMap.clocks), duplicates: new Map(hasteMap.duplicates), files: new Map(hasteMap.files), map: new Map(hasteMap.map), mocks: new Map(hasteMap.mocks), }; } const add = () => { eventsQueue.push({filePath, stat, type}); return null; }; const fileMetadata = hasteMap.files.get(relativeFilePath); // If it's not an addition, delete the file and all its metadata if (fileMetadata != null) { const moduleName = fileMetadata[H.ID]; const platform = getPlatformExtension(filePath, this._options.platforms) || H.GENERIC_PLATFORM; hasteMap.files.delete(relativeFilePath); let moduleMap = hasteMap.map.get(moduleName); if (moduleMap != null) { // We are forced to copy the object because jest-haste-map exposes // the map as an immutable entity. moduleMap = copy(moduleMap); delete moduleMap[platform]; if (Object.keys(moduleMap).length === 0) { hasteMap.map.delete(moduleName); } else { hasteMap.map.set(moduleName, moduleMap); } } if ( this._options.mocksPattern && this._options.mocksPattern.test(filePath) ) { const mockName = getMockName(filePath); hasteMap.mocks.delete(mockName); } this._recoverDuplicates(hasteMap, relativeFilePath, moduleName); } // If the file was added or changed, // parse it and update the haste map. if (type === 'add' || type === 'change') { invariant( stat, 'since the file exists or changed, it should have stats', ); const fileMetadata: FileMetaData = [ '', stat.mtime.getTime(), stat.size, 0, '', null, ]; hasteMap.files.set(relativeFilePath, fileMetadata); const promise = this._processFile( hasteMap, hasteMap.map, hasteMap.mocks, filePath, {forceInBand: true}, ); // Cleanup this._cleanup(); if (promise) { return promise.then(add); } else { // If a file in node_modules has changed, // emit an event regardless. add(); } } else { add(); } return null; }) .catch((error: Error) => { this._console.error( `jest-haste-map: watch error:\n ${error.stack}\n`, ); }); }; this._changeInterval = setInterval(emitChange, CHANGE_INTERVAL); return Promise.all(this._options.roots.map(createWatcher)).then( watchers => { this._watchers = watchers; }, ); }
type InternalHasteMap = { clocks: WatchmanClocks; duplicates: DuplicatesIndex; files: FileData; map: ModuleMapData; mocks: MockData; };
1,599
private _recoverDuplicates( hasteMap: InternalHasteMap, relativeFilePath: string, moduleName: string, ) { let dupsByPlatform = hasteMap.duplicates.get(moduleName); if (dupsByPlatform == null) { return; } const platform = getPlatformExtension(relativeFilePath, this._options.platforms) || H.GENERIC_PLATFORM; let dups = dupsByPlatform.get(platform); if (dups == null) { return; } dupsByPlatform = copyMap(dupsByPlatform); hasteMap.duplicates.set(moduleName, dupsByPlatform); dups = copyMap(dups); dupsByPlatform.set(platform, dups); dups.delete(relativeFilePath); if (dups.size !== 1) { return; } const uniqueModule = dups.entries().next().value; if (!uniqueModule) { return; } let dedupMap = hasteMap.map.get(moduleName); if (!dedupMap) { dedupMap = Object.create(null) as ModuleMapItem; hasteMap.map.set(moduleName, dedupMap); } dedupMap[platform] = uniqueModule; dupsByPlatform.delete(platform); if (dupsByPlatform.size === 0) { hasteMap.duplicates.delete(moduleName); } }
type InternalHasteMap = { clocks: WatchmanClocks; duplicates: DuplicatesIndex; files: FileData; map: ModuleMapData; mocks: MockData; };