Type-safe configuration system with validation and autocomplete support for IDE integration. Cypress provides a comprehensive configuration system that supports both E2E and component testing with extensive customization options.
Creates a type-safe configuration object with IntelliSense support and validation.
/**
* Provides automatic code completion for configuration in many popular code editors
* @param config - Configuration options for Cypress
* @returns The configuration passed in parameter (for chaining and type safety)
*/
function defineConfig<ComponentDevServerOpts = any>(
config: ConfigOptions<ComponentDevServerOpts>
): ConfigOptions;
interface ConfigOptions<ComponentDevServerOpts = any> {
/** Base URL for cy.visit() and cy.request() commands */
baseUrl?: string;
/** Default width in pixels for the application under test's viewport */
viewportWidth?: number;
/** Default height in pixels for the application under test's viewport */
viewportHeight?: number;
/** Time, in milliseconds, to wait until most DOM based commands are considered timed out */
defaultCommandTimeout?: number;
/** Time, in milliseconds, to wait for a system command to finish executing during a cy.exec() command */
execTimeout?: number;
/** Time, in milliseconds, to wait for a task to finish executing during a cy.task() command */
taskTimeout?: number;
/** Time, in milliseconds, to wait until cy.request(), cy.wait(), cy.fixture(), cy.getCookie(), cy.getCookies(), cy.setCookie(), cy.clearCookie(), cy.clearCookies(), and cy.screenshot() commands are considered timed out */
requestTimeout?: number;
/** Time, in milliseconds, to wait until cy.visit(), cy.go(), cy.reload() commands are considered timed out */
responseTimeout?: number;
/** Time, in milliseconds, to wait for page transition events or cy.visit(), cy.go(), cy.reload() commands to fire their page load events */
pageLoadTimeout?: number;
/** Whether Cypress will record a video of the test run when running headlessly */
video?: boolean;
/** Where to save videos of the test run */
videosFolder?: string;
/** Compression quality setting for recorded videos */
videoCompression?: number | false;
/** Whether Cypress will trash assets within videosFolder and screenshotsFolder before test run */
trashAssetsBeforeRuns?: boolean;
/** Whether Cypress will take a screenshot when a test fails during cypress run */
screenshotOnRunFailure?: boolean;
/** Where to save screenshots */
screenshotsFolder?: string;
/** Whether Chrome Web Security for same-origin policy and insecure mixed content is enabled */
chromeWebSecurity?: boolean;
/** Number of times to retry a failing test */
retries?: number | {
runMode: number;
openMode: number;
};
/** Path to folder where node_modules is located */
nodeVersion?: 'bundled' | 'system';
/** An array of values that the user agent will always be set to */
userAgent?: string;
/** Whether to include sensitive values in report output */
includeShadowDom?: boolean;
/** E2E specific configuration */
e2e?: E2EOptions<ComponentDevServerOpts>;
/** Component testing specific configuration */
component?: ComponentOptions<ComponentDevServerOpts>;
/** Environment variables */
env?: Record<string, any>;
}Usage Examples:
// cypress.config.js
const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:3000',
specPattern: 'cypress/e2e/**/*.cy.{js,jsx,ts,tsx}',
supportFile: 'cypress/support/e2e.js',
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
component: {
devServer: {
framework: 'create-react-app',
bundler: 'webpack',
},
specPattern: 'src/**/*.cy.{js,jsx,ts,tsx}',
supportFile: 'cypress/support/component.js'
},
viewportWidth: 1280,
viewportHeight: 720,
video: false,
screenshotOnRunFailure: true,
defaultCommandTimeout: 10000,
requestTimeout: 8000,
env: {
apiUrl: 'http://localhost:3001/api',
coverage: false
}
});Specific configuration options for end-to-end testing.
interface E2EOptions<ComponentDevServerOpts = any> {
/** Base URL for E2E tests */
baseUrl?: string;
/** A String or Array of glob patterns used to ignore spec files that would otherwise be shown in the list of specs */
excludeSpecPattern?: string | string[];
/** A String or Array of glob patterns of the test files to load */
specPattern?: string | string[];
/** Path to file to load before spec files load */
supportFile?: string | false;
/** Path to folder containing fixture files */
fixturesFolder?: string | false;
/** Enables you to plugin into various events Cypress emits */
setupNodeEvents?: (on: PluginEvents, config: PluginConfigOptions<ComponentDevServerOpts>) => void | ConfigOptions | Promise<ConfigOptions>;
/** URL used to access the Cypress application */
baseUrl?: string;
/** Whether to slow down commands by slowing down the DOM queries */
slowTestThreshold?: number;
/** Viewport orientation */
orientation?: 'portrait' | 'landscape';
/** Viewport preset */
viewportWidth?: number;
/** Viewport preset */
viewportHeight?: number;
/** List of hosts that you wish to block traffic to */
blockHosts?: string | string[];
/** Modifies obstructive third-party code */
modifyObstructiveCode?: boolean;
/** Whether to open the Cypress App in global mode */
experimentalSessionAndOrigin?: boolean;
}Specific configuration options for component testing.
interface ComponentOptions<ComponentDevServerOpts = any> {
/** A String or Array of glob patterns used to ignore spec files that would otherwise be shown in the list of specs */
excludeSpecPattern?: string | string[];
/** A String or Array of glob patterns of the test files to load */
specPattern?: string | string[];
/** Path to file to load before spec files load */
supportFile?: string | false;
/** Path to the HTML file that is used to mount components during component testing */
indexHtmlFile?: string;
/** Dev server configuration for component testing */
devServer: DevServerOptions<ComponentDevServerOpts> | DevServerFn<ComponentDevServerOpts>;
/** Enables you to plugin into various events Cypress emits */
setupNodeEvents?: (on: PluginEvents, config: PluginConfigOptions<ComponentDevServerOpts>) => void | ConfigOptions | Promise<ConfigOptions>;
}
interface DevServerOptions<ComponentDevServerOpts = any> {
/** Framework being used (react, vue, angular, etc.) */
framework: string;
/** Bundler being used (webpack, vite, etc.) */
bundler: string;
/** Port to run the dev server on */
port?: number;
/** Additional framework-specific options */
options?: ComponentDevServerOpts;
}
type DevServerFn<ComponentDevServerOpts = any> = (cypressDevServerConfig: {
specs: Spec[];
devServerEvents: NodeJS.EventEmitter;
cypressConfig: ConfigOptions<ComponentDevServerOpts>;
}) => Promise<ResolvedDevServerConfig> | ResolvedDevServerConfig;Environment variables provide a way to dynamically configure Cypress at runtime.
interface EnvironmentVariables {
/** Any environment variable can be set */
[key: string]: any;
}Environment Variable Examples:
// In cypress.config.js
module.exports = defineConfig({
env: {
// API configuration
apiUrl: 'http://localhost:3001/api',
apiTimeout: 10000,
// Authentication
username: 'test-user',
password: 'test-password',
// Feature flags
enableFeatureX: true,
debugMode: false,
// Test data paths
fixturesPath: './cypress/fixtures',
downloadsPath: './cypress/downloads'
},
e2e: {
baseUrl: process.env.CYPRESS_BASE_URL || 'http://localhost:3000',
setupNodeEvents(on, config) {
// Dynamically set environment variables
config.env.buildId = process.env.CI_BUILD_ID;
config.env.environment = process.env.NODE_ENV;
return config;
}
}
});
// Override via command line
// cypress run --env apiUrl=https://api.staging.com,debugMode=true
// Override via environment variables
// CYPRESS_apiUrl=https://api.staging.com cypress runConfiguration for handling various Cypress events and extending functionality.
interface PluginEvents {
/** Register a handler for task events */
(event: 'task', handler: Record<string, (arg: any) => any>): void;
/** Register a handler for file preprocessing */
(event: 'file:preprocessor', handler: FilePreprocessor): void;
/** Register a handler for before:browser:launch events */
(event: 'before:browser:launch', handler: BeforeBrowserLaunchHandler): void;
/** Register a handler for after:screenshot events */
(event: 'after:screenshot', handler: AfterScreenshotHandler): void;
/** Register a handler for before:spec events */
(event: 'before:spec', handler: BeforeSpecHandler): void;
/** Register a handler for after:spec events */
(event: 'after:spec', handler: AfterSpecHandler): void;
}
interface PluginConfigOptions<ComponentDevServerOpts = any> {
/** The resolved configuration object */
config: ConfigOptions<ComponentDevServerOpts>;
/** Environment variables */
env: Record<string, any>;
}Plugin Event Examples:
// In cypress.config.js
const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// Custom task for database seeding
on('task', {
seedDatabase() {
// Database seeding logic
return null;
},
log(message) {
console.log(message);
return null;
},
readFile(filename) {
return fs.readFileSync(filename, 'utf8');
}
});
// File preprocessing for TypeScript
on('file:preprocessor', require('@cypress/webpack-preprocessor')({
webpackOptions: {
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader'
}
]
}
}
}));
// Browser launch customization
on('before:browser:launch', (browser, launchOptions) => {
if (browser.name === 'chrome') {
launchOptions.args.push('--disable-dev-shm-usage');
}
return launchOptions;
});
return config;
}
}
});Cypress supports multiple configuration file formats:
// cypress.config.js (CommonJS)
const { defineConfig } = require('cypress');
module.exports = defineConfig({ /* config */ });
// cypress.config.ts (TypeScript)
import { defineConfig } from 'cypress';
export default defineConfig({ /* config */ });
// cypress.config.mjs (ES Modules)
import { defineConfig } from 'cypress';
export default defineConfig({ /* config */ });
// cypress.config.cjs (CommonJS explicit)
const { defineConfig } = require('cypress');
module.exports = defineConfig({ /* config */ });