Core functionality for Jest testing framework providing programmatic APIs for test discovery, scheduling, and CLI integration.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Programmatic interface to Jest's command-line functionality, supporting all CLI options and returning structured results. The runCLI function provides a complete CLI-compatible interface perfect for build tools, CI systems, and custom test runners.
Main function providing complete Jest CLI functionality programmatically.
/**
* Runs Jest with command-line arguments and project paths
* @param argv - Jest CLI arguments and configuration options
* @param projects - Array of project paths to run tests for
* @returns Promise resolving to test results and global configuration
*/
export async function runCLI(
argv: Config.Argv,
projects: Array<string>
): Promise<{
results: AggregatedResult;
globalConfig: Config.GlobalConfig;
}>;Basic Usage Example:
import { runCLI } from "@jest/core";
import { Config } from "@jest/types";
// Define CLI arguments similar to command line usage
const argv: Config.Argv = {
// Test discovery
testMatch: ["**/__tests__/**/*.test.js"],
testPathIgnorePatterns: ["/node_modules/", "/build/"],
// Output options
verbose: true,
coverage: true,
coverageDirectory: "./coverage",
// Execution options
maxWorkers: 4,
runInBand: false,
// Other options
bail: false,
forceExit: true,
};
const projects = ["./src", "./packages/utils"];
try {
const { results, globalConfig } = await runCLI(argv, projects);
console.log(`Tests run: ${results.numTotalTests}`);
console.log(`Tests passed: ${results.numPassedTests}`);
console.log(`Tests failed: ${results.numFailedTests}`);
console.log(`Success: ${results.success}`);
// Exit with appropriate code
process.exit(results.success ? 0 : 1);
} catch (error) {
console.error("Jest execution failed:", error);
process.exit(1);
}Important Note: When watch: true or watchAll: true is set in argv, the runCLI function will return a Promise that never resolves, as Jest enters watch mode and monitors for file changes. The function will only complete when the watch process is interrupted (Ctrl+C) or terminated externally.
Configure how Jest finds and filters test files.
const discoveryConfig: Partial<Config.Argv> = {
// Pattern matching
testMatch: ["**/__tests__/**/*.test.{js,ts}"],
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
testPathIgnorePatterns: ["/node_modules/", "/dist/"],
// Root directories
rootDir: "./src",
roots: ["<rootDir>/src", "<rootDir>/tests"],
// File extensions
moduleFileExtensions: ["js", "ts", "json"],
// Project selection
selectProjects: ["frontend", "backend"],
ignoreProjects: ["legacy"],
};Control how tests are executed and scheduled.
const executionConfig: Partial<Config.Argv> = {
// Parallelization
maxWorkers: 4,
runInBand: false, // Set to true to disable parallel execution
// Bail options
bail: 1, // Stop after first failure
// Watch mode
watch: false,
watchAll: false,
// Timeout
testTimeout: 5000,
// Cache
cache: true,
clearCache: false,
};Configure test output and reporting formats.
const outputConfig: Partial<Config.Argv> = {
// Verbosity
verbose: true,
silent: false,
// Output formats
json: false, // Output results as JSON
outputFile: "./test-results.json",
// Coverage
coverage: true,
coverageDirectory: "./coverage",
collectCoverageFrom: [
"src/**/*.{js,ts}",
"!src/**/*.test.{js,ts}",
"!src/**/*.d.ts",
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
// Reporters
reporters: [
"default",
["jest-junit", { outputDirectory: "./test-results" }],
],
// Error output
useStderr: false,
};import { runCLI } from "@jest/core";
async function runTestsForCI() {
const isCI = process.env.CI === "true";
const argv: Config.Argv = {
// Optimize for CI
maxWorkers: isCI ? 2 : 4,
cache: !isCI, // Disable cache in CI
coverage: true,
coverageReporters: ["text", "lcov", "json"],
// CI-specific options
forceExit: true,
detectOpenHandles: true,
verbose: false,
silent: false,
// Output for CI tools
json: true,
outputFile: "./test-results.json",
// Reporters for CI
reporters: [
"default",
["jest-junit", {
outputDirectory: "./test-results",
outputName: "junit.xml",
}],
],
};
const { results } = await runCLI(argv, [process.cwd()]);
// Generate additional CI artifacts
if (isCI) {
await generateCoverageReport(results);
await uploadTestResults(results);
}
return results;
}async function runWithCustomWatch() {
const argv: Config.Argv = {
watch: true,
watchman: true,
watchPathIgnorePatterns: ["/node_modules/", "/build/"],
// Watch mode specific options
onlyChanged: true,
changedFilesWithAncestor: true,
// Minimal output for watch mode
verbose: false,
coverage: false,
};
// This will run indefinitely in watch mode
const { results } = await runCLI(argv, [process.cwd()]);
// This code won't be reached in watch mode
return results;
}async function runMultiProjectTests() {
const argv: Config.Argv = {
// Multi-project configuration
projects: [
{
displayName: "frontend",
testMatch: ["<rootDir>/src/frontend/**/*.test.js"],
testEnvironment: "jsdom",
},
{
displayName: "backend",
testMatch: ["<rootDir>/src/backend/**/*.test.js"],
testEnvironment: "node",
},
{
displayName: "integration",
testMatch: ["<rootDir>/tests/integration/**/*.test.js"],
testEnvironment: "node",
testTimeout: 30000,
},
],
// Run specific projects
selectProjects: ["frontend", "backend"],
// Coverage across projects
coverage: true,
collectCoverageFrom: [
"src/**/*.js",
"!src/**/*.test.js",
],
};
const { results } = await runCLI(argv, []);
// Results will contain data from all selected projects
console.log("Project results:");
results.testResults.forEach(result => {
console.log(`${result.displayName}: ${result.numPassingTests} passed`);
});
return results;
}import * as path from "path";
import { readConfigs } from "jest-config";
async function runWithCustomConfig() {
// Load configuration from custom locations
const customArgv: Config.Argv = {
config: path.resolve("./custom-jest.config.js"),
rootDir: process.cwd(),
};
// Validate configuration before running
try {
const { globalConfig, configs } = await readConfigs(customArgv, [process.cwd()]);
console.log(`Loaded configuration for ${configs.length} projects`);
console.log(`Test timeout: ${globalConfig.testTimeout}ms`);
const { results } = await runCLI(customArgv, [process.cwd()]);
return { results, globalConfig };
} catch (configError) {
console.error("Configuration error:", configError);
throw configError;
}
}interface Config.Argv {
/** Test discovery patterns */
testMatch?: Array<string>;
testRegex?: Array<string>;
testPathIgnorePatterns?: Array<string>;
/** Execution options */
maxWorkers?: number;
runInBand?: boolean;
bail?: number | boolean;
/** Watch mode */
watch?: boolean;
watchAll?: boolean;
onlyChanged?: boolean;
/** Output options */
verbose?: boolean;
silent?: boolean;
json?: boolean;
outputFile?: string;
/** Coverage options */
coverage?: boolean;
coverageDirectory?: string;
collectCoverageFrom?: Array<string>;
coverageThreshold?: CoverageThreshold;
/** Project selection */
selectProjects?: Array<string>;
ignoreProjects?: Array<string>;
/** Configuration */
config?: string;
rootDir?: string;
roots?: Array<string>;
/** Cache options */
cache?: boolean;
clearCache?: boolean;
/** Process options */
forceExit?: boolean;
detectOpenHandles?: boolean;
/** Reporters */
reporters?: Array<string | [string, Record<string, any>]>;
/** Environment */
testEnvironment?: string;
testTimeout?: number;
}
interface CoverageThreshold {
global?: {
branches?: number;
functions?: number;
lines?: number;
statements?: number;
};
[key: string]: {
branches?: number;
functions?: number;
lines?: number;
statements?: number;
} | undefined;
}