id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
1,900 | onTestResult(
_test?: Test,
_testResult?: TestResult,
_results?: AggregatedResult,
): void {} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,901 | onTestResult(
_test?: Test,
_testResult?: TestResult,
_results?: AggregatedResult,
): void {} | type Test = (arg0: any) => boolean; |
1,902 | onTestResult(
_test?: Test,
_testResult?: TestResult,
_results?: AggregatedResult,
): void {} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,903 | onTestResult(
_test?: Test,
_testResult?: TestResult,
_results?: AggregatedResult,
): void {} | 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,904 | onTestResult(
_test?: Test,
_testResult?: TestResult,
_results?: AggregatedResult,
): void {} | 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,905 | onTestStart(_test?: Test): void {} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,906 | onTestStart(_test?: Test): void {} | type Test = (arg0: any) => boolean; |
1,907 | override onRunStart(
aggregatedResults: AggregatedResult,
options: ReporterOnStartOptions,
): void {
super.onRunStart(aggregatedResults, options);
this._estimatedTime = options.estimatedTime;
} | type ReporterOnStartOptions = {
estimatedTime: number;
showStatus: boolean;
}; |
1,908 | override onRunStart(
aggregatedResults: AggregatedResult,
options: ReporterOnStartOptions,
): void {
super.onRunStart(aggregatedResults, options);
this._estimatedTime = options.estimatedTime;
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,909 | private _printSnapshotSummary(
snapshots: SnapshotSummary,
globalConfig: Config.GlobalConfig,
) {
if (
snapshots.added ||
snapshots.filesRemoved ||
snapshots.unchecked ||
snapshots.unmatched ||
snapshots.updated
) {
let updateCommand;
const event = npm_lifecycle_event || '';
const prefix = NPM_EVENTS.has(event) ? '' : 'run ';
const isYarn =
typeof npm_config_user_agent === 'string' &&
npm_config_user_agent.includes('yarn');
const client = isYarn ? 'yarn' : 'npm';
const scriptUsesJest =
typeof npm_lifecycle_script === 'string' &&
npm_lifecycle_script.includes('jest');
if (globalConfig.watch || globalConfig.watchAll) {
updateCommand = 'press `u`';
} else if (event && scriptUsesJest) {
updateCommand = `run \`${`${client} ${prefix}${event}${
isYarn ? '' : ' --'
}`} -u\``;
} else {
updateCommand = 're-run jest with `-u`';
}
const snapshotSummary = getSnapshotSummary(
snapshots,
globalConfig,
updateCommand,
);
snapshotSummary.forEach(this.log);
this.log(''); // print empty line
}
} | type SnapshotSummary = {
added: number;
didUpdate: boolean;
failure: boolean;
filesAdded: number;
filesRemoved: number;
filesRemovedList: Array<string>;
filesUnmatched: number;
filesUpdated: number;
matched: number;
total: number;
unchecked: number;
uncheckedKeysByFile: Array<UncheckedSnapshot>;
unmatched: number;
updated: number;
}; |
1,910 | private _printSummary(
aggregatedResults: AggregatedResult,
globalConfig: Config.GlobalConfig,
) {
// If there were any failing tests and there was a large number of tests
// executed, re-print the failing results at the end of execution output.
const failedTests = aggregatedResults.numFailedTests;
const runtimeErrors = aggregatedResults.numRuntimeErrorTestSuites;
if (
failedTests + runtimeErrors > 0 &&
aggregatedResults.numTotalTestSuites > TEST_SUMMARY_THRESHOLD
) {
this.log(chalk.bold('Summary of all failing tests'));
aggregatedResults.testResults.forEach(testResult => {
const {failureMessage} = testResult;
if (failureMessage) {
this._write(
`${getResultHeader(testResult, globalConfig)}\n${failureMessage}\n`,
);
}
});
this.log(''); // print empty line
}
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,911 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.generateAnnotations(test, testResult);
if (!this.options.silent) {
this.printFullResult(test.context, testResult);
}
if (this.isLastTestSuite(aggregatedResults)) {
this.printFailedTestLogs(test, aggregatedResults);
}
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,912 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.generateAnnotations(test, testResult);
if (!this.options.silent) {
this.printFullResult(test.context, testResult);
}
if (this.isLastTestSuite(aggregatedResults)) {
this.printFailedTestLogs(test, aggregatedResults);
}
} | type Test = (arg0: any) => boolean; |
1,913 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.generateAnnotations(test, testResult);
if (!this.options.silent) {
this.printFullResult(test.context, testResult);
}
if (this.isLastTestSuite(aggregatedResults)) {
this.printFailedTestLogs(test, aggregatedResults);
}
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,914 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.generateAnnotations(test, testResult);
if (!this.options.silent) {
this.printFullResult(test.context, testResult);
}
if (this.isLastTestSuite(aggregatedResults)) {
this.printFailedTestLogs(test, aggregatedResults);
}
} | 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,915 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.generateAnnotations(test, testResult);
if (!this.options.silent) {
this.printFullResult(test.context, testResult);
}
if (this.isLastTestSuite(aggregatedResults)) {
this.printFailedTestLogs(test, aggregatedResults);
}
} | 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,916 | private generateAnnotations(
{context}: Test,
{testResults}: TestResult,
): void {
testResults.forEach(result => {
const title = [...result.ancestorTitles, result.title].join(
titleSeparator,
);
result.retryReasons?.forEach((retryReason, index) => {
this.#createAnnotation({
...this.#getMessageDetails(retryReason, context.config),
title: `RETRY ${index + 1}: ${title}`,
type: 'warning',
});
});
result.failureMessages.forEach(failureMessage => {
this.#createAnnotation({
...this.#getMessageDetails(failureMessage, context.config),
title,
type: 'error',
});
});
});
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,917 | private generateAnnotations(
{context}: Test,
{testResults}: TestResult,
): void {
testResults.forEach(result => {
const title = [...result.ancestorTitles, result.title].join(
titleSeparator,
);
result.retryReasons?.forEach((retryReason, index) => {
this.#createAnnotation({
...this.#getMessageDetails(retryReason, context.config),
title: `RETRY ${index + 1}: ${title}`,
type: 'warning',
});
});
result.failureMessages.forEach(failureMessage => {
this.#createAnnotation({
...this.#getMessageDetails(failureMessage, context.config),
title,
type: 'error',
});
});
});
} | type Test = (arg0: any) => boolean; |
1,918 | private generateAnnotations(
{context}: Test,
{testResults}: TestResult,
): void {
testResults.forEach(result => {
const title = [...result.ancestorTitles, result.title].join(
titleSeparator,
);
result.retryReasons?.forEach((retryReason, index) => {
this.#createAnnotation({
...this.#getMessageDetails(retryReason, context.config),
title: `RETRY ${index + 1}: ${title}`,
type: 'warning',
});
});
result.failureMessages.forEach(failureMessage => {
this.#createAnnotation({
...this.#getMessageDetails(failureMessage, context.config),
title,
type: 'error',
});
});
});
} | 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,919 | private generateAnnotations(
{context}: Test,
{testResults}: TestResult,
): void {
testResults.forEach(result => {
const title = [...result.ancestorTitles, result.title].join(
titleSeparator,
);
result.retryReasons?.forEach((retryReason, index) => {
this.#createAnnotation({
...this.#getMessageDetails(retryReason, context.config),
title: `RETRY ${index + 1}: ${title}`,
type: 'warning',
});
});
result.failureMessages.forEach(failureMessage => {
this.#createAnnotation({
...this.#getMessageDetails(failureMessage, context.config),
title,
type: 'error',
});
});
});
} | 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,920 | #createAnnotation({file, line, message, title, type}: AnnotationOptions) {
message = stripAnsi(
// copied from: https://github.com/actions/toolkit/blob/main/packages/core/src/command.ts
message.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A'),
);
this.log(
`\n::${type} file=${file},line=${line},title=${title}::${message}`,
);
} | type AnnotationOptions = {
file?: string;
line?: number | string;
message: string;
title: string;
type: 'error' | 'warning';
}; |
1,921 | private isLastTestSuite(results: AggregatedResult): boolean {
const passedTestSuites = results.numPassedTestSuites;
const failedTestSuites = results.numFailedTestSuites;
const totalTestSuites = results.numTotalTestSuites;
const computedTotal = passedTestSuites + failedTestSuites;
if (computedTotal < totalTestSuites) {
return false;
} else if (computedTotal === totalTestSuites) {
return true;
} else {
throw new Error(
`Sum(${computedTotal}) of passed (${passedTestSuites}) and failed (${failedTestSuites}) test suites is greater than the total number of test suites (${totalTestSuites}). Please report the bug at https://github.com/facebook/jest/issues`,
);
}
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,922 | private printFullResult(context: TestContext, results: TestResult): void {
const rootDir = context.config.rootDir;
let testDir = results.testFilePath.replace(rootDir, '');
testDir = testDir.slice(1, testDir.length);
const resultTree = this.getResultTree(
results.testResults,
testDir,
results.perfStats,
);
this.printResultTree(resultTree);
} | type TestContext = {
config: Config.ProjectConfig;
hasteFS: IHasteFS;
moduleMap: IModuleMap;
resolver: Resolver;
}; |
1,923 | private printFullResult(context: TestContext, results: TestResult): void {
const rootDir = context.config.rootDir;
let testDir = results.testFilePath.replace(rootDir, '');
testDir = testDir.slice(1, testDir.length);
const resultTree = this.getResultTree(
results.testResults,
testDir,
results.perfStats,
);
this.printResultTree(resultTree);
} | type TestContext = Record<string, unknown>; |
1,924 | private printFullResult(context: TestContext, results: TestResult): void {
const rootDir = context.config.rootDir;
let testDir = results.testFilePath.replace(rootDir, '');
testDir = testDir.slice(1, testDir.length);
const resultTree = this.getResultTree(
results.testResults,
testDir,
results.perfStats,
);
this.printResultTree(resultTree);
} | type TestContext = Global.TestContext; |
1,925 | private printFullResult(context: TestContext, results: TestResult): void {
const rootDir = context.config.rootDir;
let testDir = results.testFilePath.replace(rootDir, '');
testDir = testDir.slice(1, testDir.length);
const resultTree = this.getResultTree(
results.testResults,
testDir,
results.perfStats,
);
this.printResultTree(resultTree);
} | 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,926 | private printFullResult(context: TestContext, results: TestResult): void {
const rootDir = context.config.rootDir;
let testDir = results.testFilePath.replace(rootDir, '');
testDir = testDir.slice(1, testDir.length);
const resultTree = this.getResultTree(
results.testResults,
testDir,
results.perfStats,
);
this.printResultTree(resultTree);
} | 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,927 | private printResultTree(resultTree: ResultTree): void {
let perfMs;
if (resultTree.performanceInfo.slow) {
perfMs = ` (${chalk.red.inverse(
`${resultTree.performanceInfo.runtime} ms`,
)})`;
} else {
perfMs = ` (${resultTree.performanceInfo.runtime} ms)`;
}
if (resultTree.passed) {
this.startGroup(
`${chalk.bold.green.inverse('PASS')} ${resultTree.name}${perfMs}`,
);
resultTree.children.forEach(child => {
this.recursivePrintResultTree(child, true, 1);
});
this.endGroup();
} else {
this.log(
` ${chalk.bold.red.inverse('FAIL')} ${resultTree.name}${perfMs}`,
);
resultTree.children.forEach(child => {
this.recursivePrintResultTree(child, false, 1);
});
}
} | type ResultTree = {
children: Array<ResultTreeLeaf | ResultTreeNode>;
name: string;
passed: boolean;
performanceInfo: PerformanceInfo;
}; |
1,928 | private printFailedTestLogs(
context: Test,
testResults: AggregatedResult,
): boolean {
const rootDir = context.context.config.rootDir;
const results = testResults.testResults;
let written = false;
results.forEach(result => {
let testDir = result.testFilePath;
testDir = testDir.replace(rootDir, '');
testDir = testDir.slice(1, testDir.length);
if (result.failureMessage) {
if (!written) {
this.log('');
written = true;
}
this.startGroup(`Errors thrown in ${testDir}`);
this.log(result.failureMessage);
this.endGroup();
}
});
return written;
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,929 | private printFailedTestLogs(
context: Test,
testResults: AggregatedResult,
): boolean {
const rootDir = context.context.config.rootDir;
const results = testResults.testResults;
let written = false;
results.forEach(result => {
let testDir = result.testFilePath;
testDir = testDir.replace(rootDir, '');
testDir = testDir.slice(1, testDir.length);
if (result.failureMessage) {
if (!written) {
this.log('');
written = true;
}
this.startGroup(`Errors thrown in ${testDir}`);
this.log(result.failureMessage);
this.endGroup();
}
});
return written;
} | type Test = (arg0: any) => boolean; |
1,930 | private printFailedTestLogs(
context: Test,
testResults: AggregatedResult,
): boolean {
const rootDir = context.context.config.rootDir;
const results = testResults.testResults;
let written = false;
results.forEach(result => {
let testDir = result.testFilePath;
testDir = testDir.replace(rootDir, '');
testDir = testDir.slice(1, testDir.length);
if (result.failureMessage) {
if (!written) {
this.log('');
written = true;
}
this.startGroup(`Errors thrown in ${testDir}`);
this.log(result.failureMessage);
this.endGroup();
}
});
return written;
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,931 | function worker({
config,
globalConfig,
path,
context,
}: CoverageWorkerData): Promise<CoverageWorkerResult | null> {
return generateEmptyCoverage(
fs.readFileSync(path, 'utf8'),
path,
globalConfig,
config,
context.changedFiles && new Set(context.changedFiles),
context.sourcesRelatedToTestsInChangedFiles &&
new Set(context.sourcesRelatedToTestsInChangedFiles),
);
} | type CoverageWorkerData = {
config: Config.ProjectConfig;
context: CoverageReporterSerializedContext;
globalConfig: Config.GlobalConfig;
path: string;
}; |
1,932 | function getSnapshotSummary(
snapshots: SnapshotSummary,
globalConfig: Config.GlobalConfig,
updateCommand: string,
): Array<string> {
const summary = [];
summary.push(SNAPSHOT_SUMMARY('Snapshot Summary'));
if (snapshots.added) {
summary.push(
`${SNAPSHOT_ADDED(
`${ARROW + pluralize('snapshot', snapshots.added)} written `,
)}from ${pluralize('test suite', snapshots.filesAdded)}.`,
);
}
if (snapshots.unmatched) {
summary.push(
`${FAIL_COLOR(
`${ARROW}${pluralize('snapshot', snapshots.unmatched)} failed`,
)} from ${pluralize(
'test suite',
snapshots.filesUnmatched,
)}. ${SNAPSHOT_NOTE(
`Inspect your code changes or ${updateCommand} to update them.`,
)}`,
);
}
if (snapshots.updated) {
summary.push(
`${SNAPSHOT_UPDATED(
`${ARROW + pluralize('snapshot', snapshots.updated)} updated `,
)}from ${pluralize('test suite', snapshots.filesUpdated)}.`,
);
}
if (snapshots.filesRemoved) {
if (snapshots.didUpdate) {
summary.push(
`${SNAPSHOT_REMOVED(
`${ARROW}${pluralize(
'snapshot file',
snapshots.filesRemoved,
)} removed `,
)}from ${pluralize('test suite', snapshots.filesRemoved)}.`,
);
} else {
summary.push(
`${OBSOLETE_COLOR(
`${ARROW}${pluralize(
'snapshot file',
snapshots.filesRemoved,
)} obsolete `,
)}from ${pluralize(
'test suite',
snapshots.filesRemoved,
)}. ${SNAPSHOT_NOTE(
`To remove ${
snapshots.filesRemoved === 1 ? 'it' : 'them all'
}, ${updateCommand}.`,
)}`,
);
}
}
if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) {
const [head, ...tail] = snapshots.filesRemovedList;
summary.push(` ${DOWN_ARROW} ${DOT}${formatTestPath(globalConfig, head)}`);
tail.forEach(key => {
summary.push(` ${DOT}${formatTestPath(globalConfig, key)}`);
});
}
if (snapshots.unchecked) {
if (snapshots.didUpdate) {
summary.push(
`${SNAPSHOT_REMOVED(
`${ARROW}${pluralize('snapshot', snapshots.unchecked)} removed `,
)}from ${pluralize(
'test suite',
snapshots.uncheckedKeysByFile.length,
)}.`,
);
} else {
summary.push(
`${OBSOLETE_COLOR(
`${ARROW}${pluralize('snapshot', snapshots.unchecked)} obsolete `,
)}from ${pluralize(
'test suite',
snapshots.uncheckedKeysByFile.length,
)}. ${SNAPSHOT_NOTE(
`To remove ${
snapshots.unchecked === 1 ? 'it' : 'them all'
}, ${updateCommand}.`,
)}`,
);
}
snapshots.uncheckedKeysByFile.forEach(uncheckedFile => {
summary.push(
` ${DOWN_ARROW}${formatTestPath(
globalConfig,
uncheckedFile.filePath,
)}`,
);
uncheckedFile.keys.forEach(key => {
summary.push(` ${DOT}${key}`);
});
});
}
return summary;
} | type SnapshotSummary = {
added: number;
didUpdate: boolean;
failure: boolean;
filesAdded: number;
filesRemoved: number;
filesRemovedList: Array<string>;
filesUnmatched: number;
filesUpdated: number;
matched: number;
total: number;
unchecked: number;
uncheckedKeysByFile: Array<UncheckedSnapshot>;
unmatched: number;
updated: number;
}; |
1,933 | override onTestResult(
test: Test,
result: TestResult,
aggregatedResults: AggregatedResult,
): void {
super.testFinished(test.context.config, result, aggregatedResults);
if (!result.skipped) {
this.printTestFileHeader(
result.testFilePath,
test.context.config,
result,
);
if (!result.testExecError && !result.skipped) {
this._logTestResults(result.testResults);
}
this.printTestFileFailureMessage(
result.testFilePath,
test.context.config,
result,
);
}
super.forceFlushBufferedOutput();
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,934 | override onTestResult(
test: Test,
result: TestResult,
aggregatedResults: AggregatedResult,
): void {
super.testFinished(test.context.config, result, aggregatedResults);
if (!result.skipped) {
this.printTestFileHeader(
result.testFilePath,
test.context.config,
result,
);
if (!result.testExecError && !result.skipped) {
this._logTestResults(result.testResults);
}
this.printTestFileFailureMessage(
result.testFilePath,
test.context.config,
result,
);
}
super.forceFlushBufferedOutput();
} | type Test = (arg0: any) => boolean; |
1,935 | override onTestResult(
test: Test,
result: TestResult,
aggregatedResults: AggregatedResult,
): void {
super.testFinished(test.context.config, result, aggregatedResults);
if (!result.skipped) {
this.printTestFileHeader(
result.testFilePath,
test.context.config,
result,
);
if (!result.testExecError && !result.skipped) {
this._logTestResults(result.testResults);
}
this.printTestFileFailureMessage(
result.testFilePath,
test.context.config,
result,
);
}
super.forceFlushBufferedOutput();
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,936 | override onTestResult(
test: Test,
result: TestResult,
aggregatedResults: AggregatedResult,
): void {
super.testFinished(test.context.config, result, aggregatedResults);
if (!result.skipped) {
this.printTestFileHeader(
result.testFilePath,
test.context.config,
result,
);
if (!result.testExecError && !result.skipped) {
this._logTestResults(result.testResults);
}
this.printTestFileFailureMessage(
result.testFilePath,
test.context.config,
result,
);
}
super.forceFlushBufferedOutput();
} | 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,937 | override onTestResult(
test: Test,
result: TestResult,
aggregatedResults: AggregatedResult,
): void {
super.testFinished(test.context.config, result, aggregatedResults);
if (!result.skipped) {
this.printTestFileHeader(
result.testFilePath,
test.context.config,
result,
);
if (!result.testExecError && !result.skipped) {
this._logTestResults(result.testResults);
}
this.printTestFileFailureMessage(
result.testFilePath,
test.context.config,
result,
);
}
super.forceFlushBufferedOutput();
} | 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,938 | private _logSuite(suite: Suite, indentLevel: number) {
if (suite.title) {
this._logLine(suite.title, indentLevel);
}
this._logTests(suite.tests, indentLevel + 1);
suite.suites.forEach(suite => this._logSuite(suite, indentLevel + 1));
} | class Suite {
id: string;
parentSuite?: Suite;
description: Circus.TestNameLike;
throwOnExpectationFailure: boolean;
beforeFns: Array<QueueableFn>;
afterFns: Array<QueueableFn>;
beforeAllFns: Array<QueueableFn>;
afterAllFns: Array<QueueableFn>;
disabled: boolean;
children: Array<Suite | Spec>;
result: SuiteResult;
sharedContext?: object;
markedPending: boolean;
markedTodo: boolean;
isFocused: boolean;
constructor(attrs: Attributes) {
this.markedPending = false;
this.markedTodo = false;
this.isFocused = false;
this.id = attrs.id;
this.parentSuite = attrs.parentSuite;
this.description = convertDescriptorToString(attrs.description);
this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure;
this.beforeFns = [];
this.afterFns = [];
this.beforeAllFns = [];
this.afterAllFns = [];
this.disabled = false;
this.children = [];
this.result = {
id: this.id,
description: this.description,
fullName: this.getFullName(),
failedExpectations: [],
testPath: attrs.getTestPath(),
};
}
getFullName() {
const fullName = [];
for (
// eslint-disable-next-line @typescript-eslint/no-this-alias
let parentSuite: Suite | undefined = this;
parentSuite;
parentSuite = parentSuite.parentSuite
) {
if (parentSuite.parentSuite) {
fullName.unshift(parentSuite.description);
}
}
return fullName.join(' ');
}
disable() {
this.disabled = true;
}
pend(_message?: string) {
this.markedPending = true;
}
beforeEach(fn: QueueableFn) {
this.beforeFns.unshift(fn);
}
beforeAll(fn: QueueableFn) {
this.beforeAllFns.push(fn);
}
afterEach(fn: QueueableFn) {
this.afterFns.unshift(fn);
}
afterAll(fn: QueueableFn) {
this.afterAllFns.unshift(fn);
}
addChild(child: Suite | Spec) {
this.children.push(child);
}
status() {
if (this.disabled) {
return 'disabled';
}
if (this.markedPending) {
return 'pending';
}
if (this.result.failedExpectations.length > 0) {
return 'failed';
} else {
return 'finished';
}
}
isExecutable() {
return !this.disabled;
}
canBeReentered() {
return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0;
}
getResult() {
this.result.status = this.status();
return this.result;
}
sharedUserContext() {
if (!this.sharedContext) {
this.sharedContext = {};
}
return this.sharedContext;
}
clonedSharedUserContext() {
return this.sharedUserContext();
}
onException(...args: Parameters<Spec['onException']>) {
if (args[0] instanceof ExpectationFailed) {
return;
}
if (isAfterAll(this.children)) {
const data = {
matcherName: '',
passed: false,
expected: '',
actual: '',
error: arguments[0],
};
this.result.failedExpectations.push(expectationResultFactory(data));
} else {
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
child.onException.apply(child, args);
}
}
}
addExpectationResult(...args: Parameters<Spec['addExpectationResult']>) {
if (isAfterAll(this.children) && isFailure(args)) {
const data = args[1];
this.result.failedExpectations.push(expectationResultFactory(data));
if (this.throwOnExpectationFailure) {
throw new ExpectationFailed();
}
} else {
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
try {
child.addExpectationResult.apply(child, args);
} catch {
// keep going
}
}
}
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
execute(..._args: Array<any>) {}
} |
1,939 | private _logSuite(suite: Suite, indentLevel: number) {
if (suite.title) {
this._logLine(suite.title, indentLevel);
}
this._logTests(suite.tests, indentLevel + 1);
suite.suites.forEach(suite => this._logSuite(suite, indentLevel + 1));
} | type Suite = {
title: string;
suites: Array<Suite>;
tests: Array<AssertionResult>;
}; |
1,940 | private _logTest(test: AssertionResult, indentLevel: number) {
const status = this._getIcon(test.status);
const time = test.duration
? ` (${formatTime(Math.round(test.duration))})`
: '';
this._logLine(`${status} ${chalk.dim(test.title + time)}`, indentLevel);
} | type AssertionResult = TestResult.AssertionResult; |
1,941 | private _logTest(test: AssertionResult, indentLevel: number) {
const status = this._getIcon(test.status);
const time = test.duration
? ` (${formatTime(Math.round(test.duration))})`
: '';
this._logLine(`${status} ${chalk.dim(test.title + time)}`, indentLevel);
} | type AssertionResult = {
ancestorTitles: Array<string>;
duration?: number | null;
failureDetails: Array<unknown>;
failureMessages: Array<string>;
fullName: string;
invocations?: number;
location?: Callsite | null;
numPassingAsserts: number;
retryReasons?: Array<string>;
status: Status;
title: string;
}; |
1,942 | (test: AssertionResult): void => {
const printedTestStatus =
test.status === 'pending' ? 'skipped' : test.status;
const icon = this._getIcon(test.status);
const text = chalk.dim(`${printedTestStatus} ${test.title}`);
this._logLine(`${icon} ${text}`, indentLevel);
} | type AssertionResult = TestResult.AssertionResult; |
1,943 | (test: AssertionResult): void => {
const printedTestStatus =
test.status === 'pending' ? 'skipped' : test.status;
const icon = this._getIcon(test.status);
const text = chalk.dim(`${printedTestStatus} ${test.title}`);
this._logLine(`${icon} ${text}`, indentLevel);
} | type AssertionResult = {
ancestorTitles: Array<string>;
duration?: number | null;
failureDetails: Array<unknown>;
failureMessages: Array<string>;
fullName: string;
invocations?: number;
location?: Callsite | null;
numPassingAsserts: number;
retryReasons?: Array<string>;
status: Status;
title: string;
}; |
1,944 | runStarted(
aggregatedResults: AggregatedResult,
options: ReporterOnStartOptions,
): void {
this._estimatedTime = (options && options.estimatedTime) || 0;
this._showStatus = options && options.showStatus;
this._interval = setInterval(() => this._tick(), 1000);
this._aggregatedResults = aggregatedResults;
this._debouncedEmit();
} | type ReporterOnStartOptions = {
estimatedTime: number;
showStatus: boolean;
}; |
1,945 | runStarted(
aggregatedResults: AggregatedResult,
options: ReporterOnStartOptions,
): void {
this._estimatedTime = (options && options.estimatedTime) || 0;
this._showStatus = options && options.showStatus;
this._interval = setInterval(() => this._tick(), 1000);
this._aggregatedResults = aggregatedResults;
this._debouncedEmit();
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,946 | addTestCaseResult(test: Test, testCaseResult: TestCaseResult): void {
this._currentTestCases.push({test, testCaseResult});
if (!this._showStatus) {
this._emit();
} else {
this._debouncedEmit();
}
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,947 | addTestCaseResult(test: Test, testCaseResult: TestCaseResult): void {
this._currentTestCases.push({test, testCaseResult});
if (!this._showStatus) {
this._emit();
} else {
this._debouncedEmit();
}
} | type Test = (arg0: any) => boolean; |
1,948 | addTestCaseResult(test: Test, testCaseResult: TestCaseResult): void {
this._currentTestCases.push({test, testCaseResult});
if (!this._showStatus) {
this._emit();
} else {
this._debouncedEmit();
}
} | type TestCaseResult = AssertionResult; |
1,949 | (
snapshotData: SnapshotData,
snapshotPath: string,
): void => {
const snapshots = Object.keys(snapshotData)
.sort(naturalCompare)
.map(
key =>
`exports[${printBacktickString(key)}] = ${printBacktickString(
normalizeNewlines(snapshotData[key]),
)};`,
);
ensureDirectoryExists(snapshotPath);
fs.writeFileSync(
snapshotPath,
`${writeSnapshotVersion()}\n\n${snapshots.join('\n\n')}\n`,
);
} | type SnapshotData = Record<string, string>; |
1,950 | (
hasteFS: IHasteFS,
update: Config.SnapshotUpdateState,
snapshotResolver: SnapshotResolver,
testPathIgnorePatterns?: Config.ProjectConfig['testPathIgnorePatterns'],
): {
filesRemoved: number;
filesRemovedList: Array<string>;
} => {
const pattern = `\\.${EXTENSION}$`;
const files = hasteFS.matchFiles(pattern);
let testIgnorePatternsRegex: RegExp | null = null;
if (testPathIgnorePatterns && testPathIgnorePatterns.length > 0) {
testIgnorePatternsRegex = new RegExp(testPathIgnorePatterns.join('|'));
}
const list = files.filter(snapshotFile => {
const testPath = snapshotResolver.resolveTestPath(snapshotFile);
// ignore snapshots of ignored tests
if (testIgnorePatternsRegex && testIgnorePatternsRegex.test(testPath)) {
return false;
}
if (!fileExists(testPath, hasteFS)) {
if (update === 'all') {
fs.unlinkSync(snapshotFile);
}
return true;
}
return false;
});
return {
filesRemoved: list.length,
filesRemovedList: list,
};
} | type SnapshotResolver = {
/** Resolves from `testPath` to snapshot path. */
resolveSnapshotPath(testPath: string, snapshotExtension?: string): string;
/** Resolves from `snapshotPath` to test path. */
resolveTestPath(snapshotPath: string, snapshotExtension?: string): string;
/** Example test path, used for preflight consistency check of the implementation above. */
testPathForConsistencyCheck: string;
}; |
1,951 | (
hasteFS: IHasteFS,
update: Config.SnapshotUpdateState,
snapshotResolver: SnapshotResolver,
testPathIgnorePatterns?: Config.ProjectConfig['testPathIgnorePatterns'],
): {
filesRemoved: number;
filesRemovedList: Array<string>;
} => {
const pattern = `\\.${EXTENSION}$`;
const files = hasteFS.matchFiles(pattern);
let testIgnorePatternsRegex: RegExp | null = null;
if (testPathIgnorePatterns && testPathIgnorePatterns.length > 0) {
testIgnorePatternsRegex = new RegExp(testPathIgnorePatterns.join('|'));
}
const list = files.filter(snapshotFile => {
const testPath = snapshotResolver.resolveTestPath(snapshotFile);
// ignore snapshots of ignored tests
if (testIgnorePatternsRegex && testIgnorePatternsRegex.test(testPath)) {
return false;
}
if (!fileExists(testPath, hasteFS)) {
if (update === 'all') {
fs.unlinkSync(snapshotFile);
}
return true;
}
return false;
});
return {
filesRemoved: list.length,
filesRemovedList: list,
};
} | interface IHasteFS {
exists(path: string): boolean;
getAbsoluteFileIterator(): Iterable<string>;
getAllFiles(): Array<string>;
getDependencies(file: string): Array<string> | null;
getSize(path: string): number | null;
matchFiles(pattern: RegExp | string): Array<string>;
matchFilesWithGlob(
globs: ReadonlyArray<string>,
root: string | null,
): Set<string>;
} |
1,952 | (config: MatchSnapshotConfig) => {
const {context, hint, inlineSnapshot, isInline, matcherName, properties} =
config;
let {received} = config;
context.dontThrow && context.dontThrow();
const {currentTestName, isNot, snapshotState} = context;
if (isNot) {
throw new Error(
matcherErrorMessage(
matcherHintFromConfig(config, false),
NOT_SNAPSHOT_MATCHERS,
),
);
}
if (snapshotState == null) {
// Because the state is the problem, this is not a matcher error.
// Call generic stringify from jest-matcher-utils package
// because uninitialized snapshot state does not need snapshot serializers.
throw new Error(
`${matcherHintFromConfig(config, false)}\n\n` +
'Snapshot state must be initialized' +
`\n\n${printWithType('Snapshot state', snapshotState, stringify)}`,
);
}
const fullTestName =
currentTestName && hint
? `${currentTestName}: ${hint}`
: currentTestName || ''; // future BREAKING change: || hint
if (typeof properties === 'object') {
if (typeof received !== 'object' || received === null) {
throw new Error(
matcherErrorMessage(
matcherHintFromConfig(config, false),
`${RECEIVED_COLOR(
'received',
)} value must be an object when the matcher has ${EXPECTED_COLOR(
'properties',
)}`,
printWithType('Received', received, printReceived),
),
);
}
const propertyPass = context.equals(received, properties, [
context.utils.iterableEquality,
context.utils.subsetEquality,
]);
if (!propertyPass) {
const key = snapshotState.fail(fullTestName, received);
const matched = /(\d+)$/.exec(key);
const count = matched === null ? 1 : Number(matched[1]);
const message = () =>
`${matcherHintFromConfig(config, false)}\n\n${printSnapshotName(
currentTestName,
hint,
count,
)}\n\n${printPropertiesAndReceived(
properties,
received,
snapshotState.expand,
)}`;
return {
message,
name: matcherName,
pass: false,
};
} else {
received = deepMerge(received, properties);
}
}
const result = snapshotState.match({
error: context.error,
inlineSnapshot,
isInline,
received,
testName: fullTestName,
});
const {actual, count, expected, pass} = result;
if (pass) {
return {message: () => '', pass: true};
}
const message =
expected === undefined
? () =>
`${matcherHintFromConfig(config, true)}\n\n${printSnapshotName(
currentTestName,
hint,
count,
)}\n\n` +
`New snapshot was ${BOLD_WEIGHT('not written')}. The update flag ` +
'must be explicitly passed to write a new snapshot.\n\n' +
'This is likely because this test is run in a continuous integration ' +
'(CI) environment in which snapshots are not written by default.\n\n' +
`Received:${actual.includes('\n') ? '\n' : ' '}${bReceivedColor(
actual,
)}`
: () =>
`${matcherHintFromConfig(config, true)}\n\n${printSnapshotName(
currentTestName,
hint,
count,
)}\n\n${printSnapshotAndReceived(
expected,
actual,
received,
snapshotState.expand,
snapshotState.snapshotFormat,
)}`;
// Passing the actual and expected objects so that a custom reporter
// could access them, for example in order to display a custom visual diff,
// or create a different error message
return {
actual,
expected,
message,
name: matcherName,
pass: false,
};
} | type MatchSnapshotConfig = {
context: Context;
hint?: string;
inlineSnapshot?: string;
isInline: boolean;
matcherName: string;
properties?: object;
received: any;
}; |
1,953 | (
config: MatchSnapshotConfig,
fromPromise?: boolean,
) => {
const {context, hint, inlineSnapshot, isInline, matcherName, received} =
config;
context.dontThrow && context.dontThrow();
const {isNot, promise} = context;
if (!fromPromise) {
if (typeof received !== 'function') {
const options: MatcherHintOptions = {isNot, promise};
throw new Error(
matcherErrorMessage(
matcherHint(matcherName, undefined, '', options),
`${RECEIVED_COLOR('received')} value must be a function`,
printWithType('Received', received, printReceived),
),
);
}
}
if (isNot) {
throw new Error(
matcherErrorMessage(
matcherHintFromConfig(config, false),
NOT_SNAPSHOT_MATCHERS,
),
);
}
let error;
if (fromPromise) {
error = received;
} else {
try {
received();
} catch (e) {
error = e;
}
}
if (error === undefined) {
// Because the received value is a function, this is not a matcher error.
throw new Error(
`${matcherHintFromConfig(config, false)}\n\n${DID_NOT_THROW}`,
);
}
return _toMatchSnapshot({
context,
hint,
inlineSnapshot,
isInline,
matcherName,
received: error.message,
});
} | type MatchSnapshotConfig = {
context: Context;
hint?: string;
inlineSnapshot?: string;
isInline: boolean;
matcherName: string;
properties?: object;
received: any;
}; |
1,954 | (inlineSnapshot: InlineSnapshot) => string | type InlineSnapshot = {
snapshot: string;
frame: Frame;
node?: Expression;
}; |
1,955 | (
prettier: Prettier,
sourceFilePath: string,
sourceFileWithSnapshots: string,
snapshotMatcherNames: Array<string>,
) => {
// Resolve project configuration.
// For older versions of Prettier, do not load configuration.
const config = prettier.resolveConfig
? prettier.resolveConfig.sync(sourceFilePath, {editorconfig: true})
: null;
// Prioritize parser found in the project config.
// If not found detect the parser for the test file.
// For older versions of Prettier, fallback to a simple parser detection.
// @ts-expect-error - `inferredParser` is `string`
const inferredParser: PrettierParserName | null | undefined =
(config && typeof config.parser === 'string' && config.parser) ||
(prettier.getFileInfo
? prettier.getFileInfo.sync(sourceFilePath).inferredParser
: simpleDetectParser(sourceFilePath));
if (!inferredParser) {
throw new Error(
`Could not infer Prettier parser for file ${sourceFilePath}`,
);
}
// Snapshots have now been inserted. Run prettier to make sure that the code is
// formatted, except snapshot indentation. Snapshots cannot be formatted until
// after the initial format because we don't know where the call expression
// will be placed (specifically its indentation), so we have to do two
// prettier.format calls back-to-back.
return prettier.format(
prettier.format(sourceFileWithSnapshots, {
...config,
filepath: sourceFilePath,
}),
{
...config,
filepath: sourceFilePath,
parser: createFormattingParser(snapshotMatcherNames, inferredParser),
},
);
} | type Prettier = typeof import('prettier'); |
1,956 | (
chalkInstance: Chalk,
): DiffOptionsColor => {
const level = chalkInstance.level;
if (level === 3) {
return chalkInstance
.rgb(aForeground3[0], aForeground3[1], aForeground3[2])
.bgRgb(aBackground3[0], aBackground3[1], aBackground3[2]);
}
if (level === 2) {
return chalkInstance.ansi256(aForeground2).bgAnsi256(aBackground2);
}
return chalkInstance.magenta.bgYellowBright;
} | type Chalk = chalk.Chalk; |
1,957 | (
chalkInstance: Chalk,
): DiffOptionsColor => {
const level = chalkInstance.level;
if (level === 3) {
return chalkInstance
.rgb(bForeground3[0], bForeground3[1], bForeground3[2])
.bgRgb(bBackground3[0], bBackground3[1], bBackground3[2]);
}
if (level === 2) {
return chalkInstance.ansi256(bForeground2).bgAnsi256(bBackground2);
}
return chalkInstance.cyan.bgWhiteBright; // also known as teal
} | type Chalk = chalk.Chalk; |
1,958 | (
{
context: {isNot, promise},
hint,
inlineSnapshot,
matcherName,
properties,
}: MatchSnapshotConfig,
isUpdatable: boolean,
): string => {
const options: MatcherHintOptions = {isNot, promise};
if (isUpdatable) {
options.receivedColor = bReceivedColor;
}
let expectedArgument = '';
if (typeof properties === 'object') {
expectedArgument = PROPERTIES_ARG;
if (isUpdatable) {
options.expectedColor = noColor;
}
if (typeof hint === 'string' && hint.length !== 0) {
options.secondArgument = HINT_ARG;
options.secondArgumentColor = BOLD_WEIGHT;
} else if (typeof inlineSnapshot === 'string') {
options.secondArgument = SNAPSHOT_ARG;
if (isUpdatable) {
options.secondArgumentColor = aSnapshotColor;
} else {
options.secondArgumentColor = noColor;
}
}
} else {
if (typeof hint === 'string' && hint.length !== 0) {
expectedArgument = HINT_ARG;
options.expectedColor = BOLD_WEIGHT;
} else if (typeof inlineSnapshot === 'string') {
expectedArgument = SNAPSHOT_ARG;
if (isUpdatable) {
options.expectedColor = aSnapshotColor;
}
}
}
return matcherHint(matcherName, undefined, expectedArgument, options);
} | type MatchSnapshotConfig = {
context: Context;
hint?: string;
inlineSnapshot?: string;
isInline: boolean;
matcherName: string;
properties?: object;
received: any;
}; |
1,959 | 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,
};
}
}
} | type SnapshotMatchOptions = {
readonly testName: string;
readonly received: unknown;
readonly key?: string;
readonly inlineSnapshot?: string;
readonly isInline: boolean;
readonly error?: Error;
}; |
1,960 | async function createSnapshotResolver(
localRequire: LocalRequire,
snapshotResolverPath?: string | null,
): Promise<SnapshotResolver> {
return typeof snapshotResolverPath === 'string'
? createCustomSnapshotResolver(snapshotResolverPath, localRequire)
: createDefaultSnapshotResolver();
} | type LocalRequire = (module: string) => unknown; |
1,961 | function verifyConsistentTransformations(custom: SnapshotResolver) {
const resolvedSnapshotPath = custom.resolveSnapshotPath(
custom.testPathForConsistencyCheck,
);
const resolvedTestPath = custom.resolveTestPath(resolvedSnapshotPath);
if (resolvedTestPath !== custom.testPathForConsistencyCheck) {
throw new Error(
chalk.bold(
`Custom snapshot resolver functions must transform paths consistently, i.e. expects resolveTestPath(resolveSnapshotPath('${custom.testPathForConsistencyCheck}')) === ${resolvedTestPath}`,
),
);
}
} | type SnapshotResolver = {
/** Resolves from `testPath` to snapshot path. */
resolveSnapshotPath(testPath: string, snapshotExtension?: string): string;
/** Resolves from `snapshotPath` to test path. */
resolveTestPath(snapshotPath: string, snapshotExtension?: string): string;
/** Example test path, used for preflight consistency check of the implementation above. */
testPathForConsistencyCheck: string;
}; |
1,962 | function deepCyclicCopy<T>(
value: T,
options: DeepCyclicCopyOptions = {blacklist: EMPTY, keepPrototype: false},
cycles: WeakMap<any, any> = new WeakMap(),
): T {
if (typeof value !== 'object' || value === null || Buffer.isBuffer(value)) {
return value;
} else if (cycles.has(value)) {
return cycles.get(value);
} else if (Array.isArray(value)) {
return deepCyclicCopyArray(value, options, cycles);
} else {
return deepCyclicCopyObject(value, options, cycles);
}
} | type DeepCyclicCopyOptions = {
blacklist?: Set<string>;
keepPrototype?: boolean;
}; |
1,963 | function deepCyclicCopyObject<T>(
object: T,
options: DeepCyclicCopyOptions,
cycles: WeakMap<any, any>,
): T {
const newObject = options.keepPrototype
? Object.create(Object.getPrototypeOf(object))
: {};
const descriptors = Object.getOwnPropertyDescriptors(object);
cycles.set(object, newObject);
Object.keys(descriptors).forEach(key => {
if (options.blacklist && options.blacklist.has(key)) {
delete descriptors[key];
return;
}
const descriptor = descriptors[key];
if (typeof descriptor.value !== 'undefined') {
descriptor.value = deepCyclicCopy(
descriptor.value,
{blacklist: EMPTY, keepPrototype: options.keepPrototype},
cycles,
);
}
descriptor.configurable = true;
});
return Object.defineProperties(newObject, descriptors);
} | type DeepCyclicCopyOptions = {
blacklist?: Set<string>;
keepPrototype?: boolean;
}; |
1,964 | (meta: JestImportMeta) => {
meta.url = pathToFileURL(modulePath).href;
let jest = this.jestObjectCaches.get(modulePath);
if (!jest) {
jest = this._createJestObjectFor(modulePath);
this.jestObjectCaches.set(modulePath, jest);
}
meta.jest = jest;
} | interface JestImportMeta extends ImportMeta {
jest: Jest;
} |
1,965 | private _loadModule(
localModule: InitialModule,
from: string,
moduleName: string | undefined,
modulePath: string,
options: InternalModuleOptions | undefined,
moduleRegistry: ModuleRegistry,
) {
if (path.extname(modulePath) === '.json') {
const text = stripBOM(this.readFile(modulePath));
const transformedFile = this._scriptTransformer.transformJson(
modulePath,
this._getFullTransformationOptions(options),
text,
);
localModule.exports =
this._environment.global.JSON.parse(transformedFile);
} else if (path.extname(modulePath) === '.node') {
localModule.exports = require(modulePath);
} else {
// Only include the fromPath if a moduleName is given. Else treat as root.
const fromPath = moduleName ? from : null;
this._execModule(
localModule,
options,
moduleRegistry,
fromPath,
moduleName,
);
}
localModule.loaded = true;
} | type ModuleRegistry = Map<string, InitialModule | Module>; |
1,966 | private _loadModule(
localModule: InitialModule,
from: string,
moduleName: string | undefined,
modulePath: string,
options: InternalModuleOptions | undefined,
moduleRegistry: ModuleRegistry,
) {
if (path.extname(modulePath) === '.json') {
const text = stripBOM(this.readFile(modulePath));
const transformedFile = this._scriptTransformer.transformJson(
modulePath,
this._getFullTransformationOptions(options),
text,
);
localModule.exports =
this._environment.global.JSON.parse(transformedFile);
} else if (path.extname(modulePath) === '.node') {
localModule.exports = require(modulePath);
} else {
// Only include the fromPath if a moduleName is given. Else treat as root.
const fromPath = moduleName ? from : null;
this._execModule(
localModule,
options,
moduleRegistry,
fromPath,
moduleName,
);
}
localModule.loaded = true;
} | type InitialModule = Omit<Module, 'require' | 'parent' | 'paths'>; |
1,967 | private _getFullTransformationOptions(
options: InternalModuleOptions = defaultTransformOptions,
): TransformationOptions {
return {
...options,
...this._coverageOptions,
};
} | interface InternalModuleOptions extends Required<CallerTransformOptions> {
isInternalModule: boolean;
} |
1,968 | private _execModule(
localModule: InitialModule,
options: InternalModuleOptions | undefined,
moduleRegistry: ModuleRegistry,
from: string | null,
moduleName?: string,
) {
if (this.isTornDown) {
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
);
process.exitCode = 1;
return;
}
// If the environment was disposed, prevent this module from being executed.
if (!this._environment.global) {
return;
}
const module = localModule as Module;
const filename = module.filename;
const lastExecutingModulePath = this._currentlyExecutingModulePath;
this._currentlyExecutingModulePath = filename;
const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
this._isCurrentlyExecutingManualMock = filename;
module.children = [];
Object.defineProperty(module, 'parent', {
enumerable: true,
get() {
const key = from || '';
return moduleRegistry.get(key) || null;
},
});
const modulePaths = this._resolver.getModulePaths(module.path);
const globalPaths = this._resolver.getGlobalPaths(moduleName);
module.paths = [...modulePaths, ...globalPaths];
Object.defineProperty(module, 'require', {
value: this._createRequireImplementation(module, options),
});
const transformedCode = this.transformFile(filename, options);
let compiledFunction: ModuleWrapper | null = null;
const script = this.createScriptFromCode(transformedCode, filename);
let runScript: RunScriptEvalResult | null = null;
const vmContext = this._environment.getVmContext();
if (vmContext) {
runScript = script.runInContext(vmContext, {filename});
}
if (runScript !== null) {
compiledFunction = runScript[EVAL_RESULT_VARIABLE];
}
if (compiledFunction === null) {
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
);
process.exitCode = 1;
return;
}
const jestObject = this._createJestObjectFor(filename);
this.jestObjectCaches.set(filename, jestObject);
const lastArgs: [Jest | undefined, ...Array<Global.Global>] = [
this._config.injectGlobals ? jestObject : undefined, // jest object
...this._config.sandboxInjectedGlobals.map<Global.Global>(
globalVariable => {
if (this._environment.global[globalVariable]) {
return this._environment.global[globalVariable];
}
throw new Error(
`You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`,
);
},
),
];
if (!this._mainModule && filename === this._testPath) {
this._mainModule = module;
}
Object.defineProperty(module, 'main', {
enumerable: true,
value: this._mainModule,
});
try {
compiledFunction.call(
module.exports,
module, // module object
module.exports, // module exports
module.require, // require implementation
module.path, // __dirname
module.filename, // __filename
lastArgs[0],
...lastArgs.slice(1).filter(notEmpty),
);
} catch (error: any) {
this.handleExecutionError(error, module);
}
this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
this._currentlyExecutingModulePath = lastExecutingModulePath;
} | type ModuleRegistry = Map<string, InitialModule | Module>; |
1,969 | private _execModule(
localModule: InitialModule,
options: InternalModuleOptions | undefined,
moduleRegistry: ModuleRegistry,
from: string | null,
moduleName?: string,
) {
if (this.isTornDown) {
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
);
process.exitCode = 1;
return;
}
// If the environment was disposed, prevent this module from being executed.
if (!this._environment.global) {
return;
}
const module = localModule as Module;
const filename = module.filename;
const lastExecutingModulePath = this._currentlyExecutingModulePath;
this._currentlyExecutingModulePath = filename;
const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
this._isCurrentlyExecutingManualMock = filename;
module.children = [];
Object.defineProperty(module, 'parent', {
enumerable: true,
get() {
const key = from || '';
return moduleRegistry.get(key) || null;
},
});
const modulePaths = this._resolver.getModulePaths(module.path);
const globalPaths = this._resolver.getGlobalPaths(moduleName);
module.paths = [...modulePaths, ...globalPaths];
Object.defineProperty(module, 'require', {
value: this._createRequireImplementation(module, options),
});
const transformedCode = this.transformFile(filename, options);
let compiledFunction: ModuleWrapper | null = null;
const script = this.createScriptFromCode(transformedCode, filename);
let runScript: RunScriptEvalResult | null = null;
const vmContext = this._environment.getVmContext();
if (vmContext) {
runScript = script.runInContext(vmContext, {filename});
}
if (runScript !== null) {
compiledFunction = runScript[EVAL_RESULT_VARIABLE];
}
if (compiledFunction === null) {
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
);
process.exitCode = 1;
return;
}
const jestObject = this._createJestObjectFor(filename);
this.jestObjectCaches.set(filename, jestObject);
const lastArgs: [Jest | undefined, ...Array<Global.Global>] = [
this._config.injectGlobals ? jestObject : undefined, // jest object
...this._config.sandboxInjectedGlobals.map<Global.Global>(
globalVariable => {
if (this._environment.global[globalVariable]) {
return this._environment.global[globalVariable];
}
throw new Error(
`You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`,
);
},
),
];
if (!this._mainModule && filename === this._testPath) {
this._mainModule = module;
}
Object.defineProperty(module, 'main', {
enumerable: true,
value: this._mainModule,
});
try {
compiledFunction.call(
module.exports,
module, // module object
module.exports, // module exports
module.require, // require implementation
module.path, // __dirname
module.filename, // __filename
lastArgs[0],
...lastArgs.slice(1).filter(notEmpty),
);
} catch (error: any) {
this.handleExecutionError(error, module);
}
this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
this._currentlyExecutingModulePath = lastExecutingModulePath;
} | type InitialModule = Omit<Module, 'require' | 'parent' | 'paths'>; |
1,970 | private _createRequireImplementation(
from: InitialModule,
options?: InternalModuleOptions,
): NodeRequire {
const resolve = (moduleName: string, resolveOptions?: ResolveOptions) => {
const resolved = this._requireResolve(
from.filename,
moduleName,
resolveOptions,
);
if (
resolveOptions?.[JEST_RESOLVE_OUTSIDE_VM_OPTION] &&
options?.isInternalModule
) {
return createOutsideJestVmPath(resolved);
}
return resolved;
};
resolve.paths = (moduleName: string) =>
this._requireResolvePaths(from.filename, moduleName);
const moduleRequire = (
options?.isInternalModule
? (moduleName: string) =>
this.requireInternalModule(from.filename, moduleName)
: this.requireModuleOrMock.bind(this, from.filename)
) as NodeRequire;
moduleRequire.extensions = Object.create(null);
moduleRequire.resolve = resolve;
moduleRequire.cache = (() => {
// TODO: consider warning somehow that this does nothing. We should support deletions, anyways
const notPermittedMethod = () => true;
return new Proxy<(typeof moduleRequire)['cache']>(Object.create(null), {
defineProperty: notPermittedMethod,
deleteProperty: notPermittedMethod,
get: (_target, key) =>
typeof key === 'string' ? this._moduleRegistry.get(key) : undefined,
getOwnPropertyDescriptor() {
return {
configurable: true,
enumerable: true,
};
},
has: (_target, key) =>
typeof key === 'string' && this._moduleRegistry.has(key),
ownKeys: () => Array.from(this._moduleRegistry.keys()),
set: notPermittedMethod,
});
})();
Object.defineProperty(moduleRequire, 'main', {
enumerable: true,
value: this._mainModule,
});
return moduleRequire;
} | type InitialModule = Omit<Module, 'require' | 'parent' | 'paths'>; |
1,971 | private _createRequireImplementation(
from: InitialModule,
options?: InternalModuleOptions,
): NodeRequire {
const resolve = (moduleName: string, resolveOptions?: ResolveOptions) => {
const resolved = this._requireResolve(
from.filename,
moduleName,
resolveOptions,
);
if (
resolveOptions?.[JEST_RESOLVE_OUTSIDE_VM_OPTION] &&
options?.isInternalModule
) {
return createOutsideJestVmPath(resolved);
}
return resolved;
};
resolve.paths = (moduleName: string) =>
this._requireResolvePaths(from.filename, moduleName);
const moduleRequire = (
options?.isInternalModule
? (moduleName: string) =>
this.requireInternalModule(from.filename, moduleName)
: this.requireModuleOrMock.bind(this, from.filename)
) as NodeRequire;
moduleRequire.extensions = Object.create(null);
moduleRequire.resolve = resolve;
moduleRequire.cache = (() => {
// TODO: consider warning somehow that this does nothing. We should support deletions, anyways
const notPermittedMethod = () => true;
return new Proxy<(typeof moduleRequire)['cache']>(Object.create(null), {
defineProperty: notPermittedMethod,
deleteProperty: notPermittedMethod,
get: (_target, key) =>
typeof key === 'string' ? this._moduleRegistry.get(key) : undefined,
getOwnPropertyDescriptor() {
return {
configurable: true,
enumerable: true,
};
},
has: (_target, key) =>
typeof key === 'string' && this._moduleRegistry.has(key),
ownKeys: () => Array.from(this._moduleRegistry.keys()),
set: notPermittedMethod,
});
})();
Object.defineProperty(moduleRequire, 'main', {
enumerable: true,
value: this._mainModule,
});
return moduleRequire;
} | interface InternalModuleOptions extends Required<CallerTransformOptions> {
isInternalModule: boolean;
} |
1,972 | private handleExecutionError(e: Error, module: Module): never {
const moduleNotFoundError = Resolver.tryCastModuleNotFoundError(e);
if (moduleNotFoundError) {
if (!moduleNotFoundError.requireStack) {
moduleNotFoundError.requireStack = [module.filename || module.id];
for (let cursor = module.parent; cursor; cursor = cursor.parent) {
moduleNotFoundError.requireStack.push(cursor.filename || cursor.id);
}
moduleNotFoundError.buildMessage(this._config.rootDir);
}
throw moduleNotFoundError;
}
throw e;
} | type Module = NodeModule; |
1,973 | setGlobalsForRuntime(globals: JestGlobals): void {
this.jestGlobals = globals;
} | interface JestGlobals extends Global.TestFrameworkGlobals {
// we cannot type `expect` properly as it'd create circular dependencies
expect: unknown;
} |
1,974 | setGlobalsForRuntime(globals: JestGlobals): void {
this.jestGlobals = globals;
} | interface JestGlobals extends Global.TestFrameworkGlobals {
expect: typeof expect;
} |
1,975 | function addIstanbulInstrumentation(
babelOptions: TransformOptions,
transformOptions: JestTransformOptions,
): TransformOptions {
if (transformOptions.instrument) {
const copiedBabelOptions: TransformOptions = {...babelOptions};
copiedBabelOptions.auxiliaryCommentBefore = ' istanbul ignore next ';
// Copied from jest-runtime transform.js
copiedBabelOptions.plugins = (copiedBabelOptions.plugins ?? []).concat([
[
babelIstanbulPlugin,
{
// files outside `cwd` will not be instrumented
cwd: transformOptions.config.cwd,
exclude: [],
},
],
]);
return copiedBabelOptions;
}
return babelOptions;
} | interface TransformOptions<TransformerConfig = unknown>
extends ReducedTransformOptions {
/** Cached file system which is used by `jest-runtime` to improve performance. */
cacheFS: StringMap;
/** Jest configuration of currently running project. */
config: Config.ProjectConfig;
/** Stringified version of the `config` - useful in cache busting. */
configString: string;
/** Transformer configuration passed through `transform` option by the user. */
transformerConfig: TransformerConfig;
} |
1,976 | forEach(cb: ReplaceableForEachCallBack): void {
if (this.type === 'object') {
const descriptors = Object.getOwnPropertyDescriptors(this.object);
[
...Object.keys(descriptors),
...Object.getOwnPropertySymbols(descriptors),
]
//@ts-expect-error because typescript do not support symbol key in object
//https://github.com/microsoft/TypeScript/issues/1863
.filter(key => descriptors[key].enumerable)
.forEach(key => {
cb(this.object[key], key, this.object);
});
} else {
this.object.forEach(cb);
}
} | type ReplaceableForEachCallBack = (
value: unknown,
key: unknown,
object: unknown,
) => void; |
1,977 | function summarize(coverageMap: CoverageMap): CoverageMap {
if (!coverageMap) {
return coverageMap;
}
const summaries = Object.create(null);
coverageMap.files().forEach(file => {
const covered = [];
const lineCoverage = coverageMap.fileCoverageFor(file).getLineCoverage();
Object.keys(lineCoverage).forEach(lineNumber => {
const number = parseInt(lineNumber, 10);
// Line numbers start at one
covered[number - 1] = lineCoverage[number] ? 'C' : 'U';
});
for (let i = 0; i < covered.length; i++) {
if (!covered[i]) {
covered[i] = 'N';
}
}
summaries[file] = covered.join('');
});
return summaries;
} | type CoverageMap = AggregatedResult['coverageMap']; |
1,978 | function PhabricatorProcessor(
results: AggregatedResult,
): AggregatedResult {
return {...results, coverageMap: summarize(results.coverageMap)};
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,979 | constructor(argument: Expression) {
this.type = Syntax.AwaitExpression;
this.argument = argument;
} | type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression |
AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression |
ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression |
RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression |
ThisExpression | UnaryExpression | UpdateExpression | YieldExpression; |
1,980 | constructor(expression: ChainElement) {
this.type = Syntax.ChainExpression;
this.expression = expression;
} | type ChainElement = CallExpression | ComputedMemberExpression | StaticMemberExpression; |
1,981 | constructor(object: Expression, property: Expression, optional: boolean) {
this.type = Syntax.MemberExpression;
this.computed = true;
this.object = object;
this.property = property;
this.optional = optional;
} | type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression |
AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression |
ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression |
RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression |
ThisExpression | UnaryExpression | UpdateExpression | YieldExpression; |
1,982 | constructor(test: Expression, consequent: Expression, alternate: Expression) {
this.type = Syntax.ConditionalExpression;
this.test = test;
this.consequent = consequent;
this.alternate = alternate;
} | type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression |
AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression |
ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression |
RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression |
ThisExpression | UnaryExpression | UpdateExpression | YieldExpression; |
1,983 | constructor(expression: Expression, directive: string) {
this.type = Syntax.ExpressionStatement;
this.expression = expression;
this.directive = directive;
} | type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression |
AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression |
ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression |
RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression |
ThisExpression | UnaryExpression | UpdateExpression | YieldExpression; |
1,984 | constructor(body: Statement, test: Expression) {
this.type = Syntax.DoWhileStatement;
this.body = body;
this.test = test;
} | type Statement = AsyncFunctionDeclaration | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement |
EmptyStatement | ExpressionStatement | Directive | ForStatement | ForInStatement | ForOfStatement |
FunctionDeclaration | IfStatement | ReturnStatement | SwitchStatement | ThrowStatement |
TryStatement | VariableDeclaration | WhileStatement | WithStatement; |
1,985 | constructor(body: Statement, test: Expression) {
this.type = Syntax.DoWhileStatement;
this.body = body;
this.test = test;
} | type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression |
AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression |
ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression |
RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression |
ThisExpression | UnaryExpression | UpdateExpression | YieldExpression; |
1,986 | constructor(source: Literal) {
this.type = Syntax.ExportAllDeclaration;
this.source = source;
} | class Literal {
readonly type: string;
readonly value: boolean | number | string | null;
readonly raw: string;
constructor(value: boolean | number | string | null, raw: string) {
this.type = Syntax.Literal;
this.value = value;
this.raw = raw;
}
} |
1,987 | constructor(declaration: ExportableDefaultDeclaration) {
this.type = Syntax.ExportDefaultDeclaration;
this.declaration = declaration;
} | type ExportableDefaultDeclaration = BindingIdentifier | BindingPattern | ClassDeclaration | Expression | FunctionDeclaration; |
1,988 | constructor(local: Identifier, exported: Identifier) {
this.type = Syntax.ExportSpecifier;
this.exported = exported;
this.local = local;
} | class Identifier {
readonly type: string;
readonly name: string;
constructor(name) {
this.type = Syntax.Identifier;
this.name = name;
}
} |
1,989 | constructor(expression: Expression) {
this.type = Syntax.ExpressionStatement;
this.expression = expression;
} | type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression |
AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression |
ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression |
RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression |
ThisExpression | UnaryExpression | UpdateExpression | YieldExpression; |
1,990 | constructor(left: Expression, right: Expression, body: Statement) {
this.type = Syntax.ForInStatement;
this.left = left;
this.right = right;
this.body = body;
this.each = false;
} | type Statement = AsyncFunctionDeclaration | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement |
EmptyStatement | ExpressionStatement | Directive | ForStatement | ForInStatement | ForOfStatement |
FunctionDeclaration | IfStatement | ReturnStatement | SwitchStatement | ThrowStatement |
TryStatement | VariableDeclaration | WhileStatement | WithStatement; |
1,991 | constructor(left: Expression, right: Expression, body: Statement) {
this.type = Syntax.ForInStatement;
this.left = left;
this.right = right;
this.body = body;
this.each = false;
} | type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression |
AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression |
ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression |
RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression |
ThisExpression | UnaryExpression | UpdateExpression | YieldExpression; |
1,992 | constructor(left: Expression, right: Expression, body: Statement, _await: boolean) {
this.type = Syntax.ForOfStatement;
this.await = _await;
this.left = left;
this.right = right;
this.body = body;
} | type Statement = AsyncFunctionDeclaration | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement |
EmptyStatement | ExpressionStatement | Directive | ForStatement | ForInStatement | ForOfStatement |
FunctionDeclaration | IfStatement | ReturnStatement | SwitchStatement | ThrowStatement |
TryStatement | VariableDeclaration | WhileStatement | WithStatement; |
1,993 | constructor(left: Expression, right: Expression, body: Statement, _await: boolean) {
this.type = Syntax.ForOfStatement;
this.await = _await;
this.left = left;
this.right = right;
this.body = body;
} | type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression |
AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression |
ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression |
RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression |
ThisExpression | UnaryExpression | UpdateExpression | YieldExpression; |
1,994 | constructor(test: Expression, consequent: Statement, alternate: Statement | null) {
this.type = Syntax.IfStatement;
this.test = test;
this.consequent = consequent;
this.alternate = alternate;
} | type Statement = AsyncFunctionDeclaration | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement |
EmptyStatement | ExpressionStatement | Directive | ForStatement | ForInStatement | ForOfStatement |
FunctionDeclaration | IfStatement | ReturnStatement | SwitchStatement | ThrowStatement |
TryStatement | VariableDeclaration | WhileStatement | WithStatement; |
1,995 | constructor(test: Expression, consequent: Statement, alternate: Statement | null) {
this.type = Syntax.IfStatement;
this.test = test;
this.consequent = consequent;
this.alternate = alternate;
} | type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression |
AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression |
ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression |
RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression |
ThisExpression | UnaryExpression | UpdateExpression | YieldExpression; |
1,996 | constructor(local: Identifier) {
this.type = Syntax.ImportDefaultSpecifier;
this.local = local;
} | class Identifier {
readonly type: string;
readonly name: string;
constructor(name) {
this.type = Syntax.Identifier;
this.name = name;
}
} |
1,997 | constructor(local: Identifier) {
this.type = Syntax.ImportNamespaceSpecifier;
this.local = local;
} | class Identifier {
readonly type: string;
readonly name: string;
constructor(name) {
this.type = Syntax.Identifier;
this.name = name;
}
} |
1,998 | constructor(local: Identifier, imported: Identifier) {
this.type = Syntax.ImportSpecifier;
this.local = local;
this.imported = imported;
} | class Identifier {
readonly type: string;
readonly name: string;
constructor(name) {
this.type = Syntax.Identifier;
this.name = name;
}
} |
1,999 | constructor(label: Identifier, body: Statement) {
this.type = Syntax.LabeledStatement;
this.label = label;
this.body = body;
} | type Statement = AsyncFunctionDeclaration | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement |
EmptyStatement | ExpressionStatement | Directive | ForStatement | ForInStatement | ForOfStatement |
FunctionDeclaration | IfStatement | ReturnStatement | SwitchStatement | ThrowStatement |
TryStatement | VariableDeclaration | WhileStatement | WithStatement; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.