### Complete CI/CD Setup Example Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md A comprehensive bash script example for setting up authentication, build identification, local testing, test configuration, Cypress Cloud, and running tests with BrowserStack. ```bash #!/bin/bash # Authentication export BROWSERSTACK_USERNAME=${BS_USERNAME} export BROWSERSTACK_ACCESS_KEY=${BS_ACCESS_KEY} # Build identification export BROWSERSTACK_BUILD_NAME="CI-Build-${CI_COMMIT_SHA:0:8}" export BROWSERSTACK_PROJECT_NAME="MyProject" # Local testing (if needed) export BROWSERSTACK_LOCAL=true export BROWSERSTACK_LOCAL_IDENTIFIER="ci-${CI_JOB_ID}" # Test configuration export BROWSERSTACK_CYPRESS_TIMEZONE="UTC" export BROWSERSTACK_CYPRESS_SPEC_TIMEOUT=45 # Cypress Cloud export CYPRESS_RECORD_KEY=${CYPRESS_KEY} export CYPRESS_PROJECT_ID=${CYPRESS_PROJECT} # Testing browserstack-cypress run \ --config-file ./browserstack.json \ --specs "cypress/e2e/**/*.cy.js" \ --parallels 5 ``` -------------------------------- ### Browser Object Configuration Example Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md This example demonstrates how to define multiple browser and OS combinations for testing, including specifying browser versions. ```json "browsers": [ { "browser": "chrome", "os": "Windows 10", "versions": ["latest", "latest-1"] }, { "browser": "firefox", "os": "OS X Monterey", "versions": ["latest"] } ] ``` -------------------------------- ### Example browserstack.json Configuration Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md This is a comprehensive example of the `browserstack.json` file, illustrating the structure for authentication, browser definitions, run settings, and connection preferences. ```json { "auth": { "username": "", "access_key": "" }, "browsers": [ { "browser": "chrome", "os": "Windows 10", "versions": ["latest", "latest-1"] } ], "run_settings": { "cypress_config_file": "/path/to/cypress.json", "project_name": "project-name", "build_name": "build-name", "exclude": [], "parallels": 2, "npm_dependencies": {}, "auto_import_dev_dependencies": false, "exclude_dependencies": [], "package_config_options": {}, "headless": true }, "connection_settings": { "local": false, "local_identifier": null, "local_mode": null, "local_config_file": null }, "disable_usage_reporting": false } ``` -------------------------------- ### Configuration Priority Example: CLI Override Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Demonstrates how CLI arguments override configuration file settings. ```bash # CLI argument overrides config file browserstack-cypress run -u override_username ``` -------------------------------- ### Install BrowserStack Cypress CLI Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/README.md Install the BrowserStack Cypress CLI globally using npm. This command is the first step to using the CLI for running Cypress tests on BrowserStack. ```bash # Install the BrowserStack Cypress CLI $ npm install -g browserstack-cypress-cli ``` -------------------------------- ### Configuration Priority Example: Environment Variable Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Demonstrates how environment variables override configuration file settings when no CLI argument is provided. ```bash # Environment variable without CLI arg BROWSERSTACK_USERNAME=env_username browserstack-cypress run ``` -------------------------------- ### Local Config File Format (YAML) Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Example format for a local configuration file in YAML, including server, port, and authentication details. ```yaml server: localhost port: 3000 automate: username: access_key: ``` -------------------------------- ### Configuration Priority Example: Config File Default Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Illustrates that the configuration file value is used if no CLI argument or environment variable is set. ```bash # Config file value used if no CLI or env browserstack-cypress run ``` -------------------------------- ### Get Initial Details Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md Retrieves project metadata and account information necessary for subsequent API calls. Requires project and build names. ```APIDOC ## POST /automate/cypress/v1/get_initial_details ### Description Retrieve project metadata and account information. ### Method POST ### Endpoint /automate/cypress/v1/get_initial_details ### Parameters #### Request Body - **project_name** (string) - Required - The name of the project. - **build_name** (string) - Required - The name of the build. ### Request Example ```json { "project_name": "project-name", "build_name": "build-1" } ``` ### Response #### Success Response (200) - **account_name** (string) - The name of the account. - **account_email** (string) - The email of the account. - **buildId** (string) - The unique identifier for the build. - **project_info** (object) - Information about the project. - **name** (string) - The name of the project. - **build_count** (integer) - The total number of builds for the project. #### Response Example ```json { "account_name": "username", "account_email": "user@example.com", "buildId": "12345678", "project_info": { "name": "project-name", "build_count": 125 } } ``` ``` -------------------------------- ### Get Initial Project Details Response Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md Response containing account details, build ID, and project information. This data is crucial for interacting with the BrowserStack platform. ```json { "account_name": "username", "account_email": "user@example.com", "buildId": "12345678", "project_info": { "name": "project-name", "build_count": 125 } } ``` -------------------------------- ### Get Initial Project Details Request Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md Retrieve project metadata and account information by sending the project name and build name. Used to fetch details necessary for subsequent operations. ```json { "project_name": "project-name", "build_name": "build-1" } ``` -------------------------------- ### Example .gitignore for BrowserStack Configuration Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md Use this .gitignore configuration to prevent committing sensitive BrowserStack configuration files and environment variables to version control. ```gitignore browserstack.json .env .env.local ``` -------------------------------- ### Get Build Info Endpoint Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md The GET endpoint for retrieving information about a specific build using its ID. ```http GET /automate/cypress/v1/builds/{buildId} ``` -------------------------------- ### Get Host Information Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Retrieves information about the host system, such as the platform. Useful for environment-specific logic. ```javascript exports.getHostInfo = () => HostInfo ``` ```javascript const hostInfo = helper.getHostInfo(); console.log(`Platform: ${hostInfo.platform}`); ``` -------------------------------- ### Get BrowserStack Build Information Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Retrieve build information using the build ID. Custom credentials can be provided to override configuration file settings. ```bash browserstack-cypress build-info 12345678 ``` ```bash browserstack-cypress build-info 12345678 -u myuser -k mykey ``` -------------------------------- ### Get Build Info Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md Retrieves detailed information about a specific BrowserStack build, including its status, duration, and session details. ```APIDOC ## GET /automate/cypress/v1/builds/{buildId} ### Description Retrieve information about a specific build. ### Method GET ### Endpoint /automate/cypress/v1/builds/{buildId} ### Parameters #### Path Parameters - **buildId** (string) - Required - The ID of the build to retrieve information for. ### Response #### Success Response (200) - **build_id** (string) - The unique identifier for the build. - **build_name** (string) - The name of the build. - **project_name** (string) - The name of the project. - **status** (string) - The current status of the build (e.g., running, completed, failed). - **duration** (integer) - The total duration of the build in seconds. - **created_at** (string) - Timestamp when the build was created. - **updated_at** (string) - Timestamp when the build was last updated. - **passed** (integer) - Number of tests that passed. - **failed** (integer) - Number of tests that failed. - **skipped** (integer) - Number of tests that were skipped. - **sessions** (array) - An array of session objects, each containing details about individual test sessions. #### Response Example ```json { "build_id": "12345678", "build_name": "build-1", "project_name": "project-name", "status": "completed", "duration": 1245, "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:51:00Z", "passed": 45, "failed": 2, "skipped": 3, "sessions": [ { "id": "session-123", "browser": "chrome", "os": "Windows 10", "version": "latest", "status": "completed", "passed": 15, "failed": 1, "skipped": 1, "duration": 400 } ] } ``` ``` -------------------------------- ### Upload NPM Packages Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md Uploads a .tar.gz archive of npm packages to BrowserStack for dependency installation during test execution. ```APIDOC ## POST /automate-frameworks/cypress/upload-npm ### Description Upload node_modules archive for dependency installation. ### Method POST ### Endpoint /automate-frameworks/cypress/upload-npm ### Parameters #### Request - **file** (multipart/form-data) - Required - The .tar.gz archive containing npm packages. ### Response #### Success Response (200) - **npm_package_url** (string) - The S3 URL of the uploaded npm package archive. - **md5_checksum** (string) - The MD5 checksum of the uploaded archive. - **package_size** (integer) - The size of the uploaded npm package archive in bytes. #### Response Example ```json { "npm_package_url": "s3://browserstack-uploads/npm.tar.gz", "md5_checksum": "a1b2c3d4e5f6...", "package_size": 52428800 } ``` ``` -------------------------------- ### User-Agent Header Example Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md Include a User-Agent header in API requests to identify the client and its version. ```http User-Agent: browserstack-cypress-cli/ (node ; ) ``` -------------------------------- ### Set Node.js Environment Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md Export NODE_ENV to set the Node.js environment, for example, to 'production'. ```bash export NODE_ENV=production browserstack-cypress run ``` -------------------------------- ### GitHub Actions Example for Running BrowserStack Tests Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md This GitHub Actions workflow demonstrates how to set BrowserStack credentials as environment variables using GitHub Secrets and then run BrowserStack Cypress tests. ```yaml - name: Run BrowserStack Tests env: BROWSERSTACK_USERNAME: ${{ secrets.BS_USERNAME }} BROWSERSTACK_ACCESS_KEY: ${{ secrets.BS_ACCESS_KEY }} run: | browserstack-cypress run ``` -------------------------------- ### ArtifactDownloadData Structure Example Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/types.md Specifies the structure for defining which artifacts to download, mapping browser-OS combinations to session IDs and artifact URLs. Used in artifact downloads. ```typescript interface ArtifactDownloadData { [browserOsCombination: string]: { [sessionId: string]: string; // URL to artifact zip }; } ``` ```json { "chrome-Windows10": { "session_123": "https://browserstack.com/artifacts/session_123.zip", "session_124": "https://browserstack.com/artifacts/session_124.zip" } } ``` -------------------------------- ### Get Build Artifacts Response Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md Response containing URLs for downloading test artifacts, organized by browser and operating system. Artifacts include videos, screenshots, and logs. ```json { "chrome-Windows10": { "session-123": "https://s3.amazonaws.com/artifacts/session-123.zip", "session-124": "https://s3.amazonaws.com/artifacts/session-124.zip" }, "firefox-Windows10": { "session-125": "https://s3.amazonaws.com/artifacts/session-125.zip" } } ``` -------------------------------- ### Get Build Info Success Response Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md A successful response (HTTP 200) for retrieving build information, including status, duration, and session details. ```json { "build_id": "12345678", "build_name": "build-1", "project_name": "project-name", "status": "completed", "duration": 1245, "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:51:00Z", "passed": 45, "failed": 2, "skipped": 3, "sessions": [ { "id": "session-123", "browser": "chrome", "os": "Windows 10", "version": "latest", "status": "completed", "passed": 15, "failed": 1, "skipped": 1, "duration": 400 } ] } ``` -------------------------------- ### Run BrowserStack Cypress Tests with Default Configuration Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Execute Cypress tests using the default browserstack.json configuration. This is the simplest way to start a test run. ```bash browserstack-cypress run ``` -------------------------------- ### Authentication Header Example Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md All API requests require HTTP Basic Authentication using your username and access key. ```http Authorization: Basic base64(username:access_key) ``` -------------------------------- ### Upload NPM Packages Endpoint Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md The POST endpoint for uploading an npm_package archive for dependency installation. ```http POST /automate-frameworks/cypress/upload-npm ``` -------------------------------- ### Get Build Artifacts Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md Retrieves URLs for downloading test artifacts associated with a specific build ID. Artifacts include videos, screenshots, and logs. ```APIDOC ## GET /automate/cypress/v1/builds/{buildId}/artifacts ### Description Retrieve URLs for downloading test artifacts. ### Method GET ### Endpoint /automate/cypress/v1/builds/{buildId}/artifacts ### Parameters #### Path Parameters - **buildId** (string) - Required - The ID of the build for which to retrieve artifacts. ### Response #### Success Response (200) - **(object)** - A map where keys are browser/OS combinations and values are objects containing session artifact URLs. - **(string)** - Session ID. - **(string)** - Pre-signed URL for the artifact zip file. #### Response Example ```json { "chrome-Windows10": { "session-123": "https://s3.amazonaws.com/artifacts/session-123.zip", "session-124": "https://s3.amazonaws.com/artifacts/session-124.zip" }, "firefox-Windows10": { "session-125": "https://s3.amazonaws.com/artifacts/session-125.zip" } } ``` ``` -------------------------------- ### Set Custom Build Names with CI/CD Variables Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Dynamically set custom build names using CI/CD environment variables for better traceability. Examples are provided for GitHub Actions, GitLab CI, and Jenkins. ```bash # GitHub Actions browserstack-cypress run -b "CI-${{ github.run_number }}" # GitLab CI browserstack-cypress run -b "CI-$CI_JOB_ID" # Jenkins browserstack-cypress run -b "Build-$BUILD_NUMBER" ``` -------------------------------- ### Using Utility Functions Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Demonstrates how to import and use utility functions for configuration validation and setting overrides. ```javascript const utils = require('./helpers/utils'); // Validate config const config = await utils.validateBstackJson(configPath); // Override settings utils.setUsername(config, { u: 'myuser' }); utils.setBuildName(config, { b: 'my-build' }); // Send analytics utils.sendUsageReport(config, args, 'Build started', 'info', null, reportData, rawArgs); ``` -------------------------------- ### Initialize BrowserStack Configuration Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/README.md Create a sample browserstack.json configuration file. This file is used to set up BrowserStack credentials, desired browsers, and run settings for your Cypress tests. ```bash # Create a sample configuration file for configurations and capabilities $ browserstack-cypress init ``` -------------------------------- ### Excluding npm Dependencies Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Exclude specific npm dependencies from being installed or used. ```json "npm_dependencies": { "large-package": "^1.0.0" }, "exclude_dependencies": [ "large-package" ] ``` -------------------------------- ### Retrieve Initial Build and Project Details Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Fetches initial project metadata and account status from the BrowserStack API. Returns build report data. ```javascript const reportData = await getInitialDetails(bsConfig, args, rawArgs); console.log(`Account: ${reportData.accountName}`); ``` -------------------------------- ### Get Package Version Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Retrieves the version of a specified package. Useful for dependency checks and reporting. ```javascript exports.getPackageVersion = (packageName, bsConfig?) => string | undefined ``` ```javascript const version = helper.getPackageVersion('cypress'); console.log(`Cypress version: ${version}`); ``` -------------------------------- ### Control Parallelization Aggressiveness Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md Set BROWSERSTACK_PARALLELIZATION_FACTOR to control the aggressiveness of parallelization. For example, set it to 2. ```bash export BROWSERSTACK_PARALLELIZATION_FACTOR=2 browserstack-cypress run ``` -------------------------------- ### Initialize browserstack.json Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Creates a new BrowserStack Cypress configuration file in the current directory. This is the default behavior when no filename or path is specified. ```bash browserstack-cypress init ``` -------------------------------- ### Get Git Metadata Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Asynchronously retrieves Git metadata, including the branch name. Used for CI/CD integration. ```javascript exports.getGitMetaData = () => Promise ``` ```javascript const gitData = await helper.getGitMetaData(); console.log(`Branch: ${gitData.branch}`); ``` -------------------------------- ### Configure Local Binary with YAML File Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Use a YAML configuration file for advanced settings of the local binary, including hosts, logging, and parallel runs. Specify the file path using the --local-config-file flag. ```yaml key: parallelRuns: 5 folder: /path/to/local/files hosts: - name: example.local port: 3000 - name: app.dev port: 5000 logFile: local-logs.txt logLevel: debug verbose: true onlyAutomate: true ``` ```bash browserstack-cypress run --local --local-config-file ./local.yml ``` -------------------------------- ### getInitialDetails Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Retrieves initial project metadata and account information from the BrowserStack API. ```APIDOC ## getInitialDetails(bsConfig, args, rawArgs) ### Description Get initial project metadata from BrowserStack API. ### Parameters - `bsConfig` (BrowserStackConfig) - Required - BrowserStackConfig object - `args` (object) - Required - CLI arguments - `rawArgs` (array) - Required - Raw command line arguments ### Returns Promise containing project info, account status, etc. ### Example ```javascript const reportData = await getInitialDetails(bsConfig, args, rawArgs); console.log(`Account: ${reportData.accountName}`); ``` ``` -------------------------------- ### Using Local Config File for Connection Settings Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Specify a local configuration file for connection settings, such as server and port. ```json "connection_settings": { "local": true, "local_config_file": "/path/to/local.yml" } ``` -------------------------------- ### Retrieve Detailed Build Information Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Fetch comprehensive build information for analysis using the `browserstack-cypress build-info` command. Piping the output to `jq '.'` formats it for readability. ```bash browserstack-cypress build-info | jq '.' ``` -------------------------------- ### createBuild Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Creates a new build on BrowserStack using the provided configuration, zip file details, capabilities, and arguments. ```APIDOC ## createBuild(bsConfig, zip, caps, args, rawArgs) ### Description Creates a build on BrowserStack with specified capabilities. ### Parameters - `bsConfig` (BrowserStackConfig) - Required - BrowserStackConfig object - `zip` (object) - Required - Object with `zip_url` and `npm_package_url` - `caps` (string) - Required - JSON string of capabilities (from capabilityHelper.caps) - `args` (object) - Required - CLI arguments - `rawArgs` (array) - Required - Raw command line arguments ### Returns Promise ### Example ```javascript const buildId = await build.createBuild(bsConfig, zip, capsJson, args, rawArgs); console.log(`Build created: ${buildId}`); ``` ``` -------------------------------- ### Enable Local Testing Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Configure connection settings to enable local testing through BrowserStack. ```json "connection_settings": { "local": true, "local_identifier": "my-local-session", "local_mode": "always-on" } ``` -------------------------------- ### Create Build on BrowserStack Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Creates a new build on BrowserStack. Requires BrowserStack configuration, zip/npm details, capabilities, and CLI arguments. ```javascript const buildId = await build.createBuild(bsConfig, zip, capsJson, args, rawArgs); console.log(`Build created: ${buildId}`); ``` -------------------------------- ### Enable Cypress Cloud Recording Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Configure the CLI to record test runs to Cypress Cloud. You must provide a record key and a project ID for this functionality. ```bash browserstack-cypress run --record --record-key myrecordkey --projectId myprojectid ``` -------------------------------- ### Enable Local Testing Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md Enable local testing for localhost or private URLs. Default is false. ```bash export BROWSERSTACK_LOCAL=true browserstack-cypress run ``` -------------------------------- ### Example Accessibility Test in Cypress Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md A basic Cypress test case that visits a URL. Accessibility violations are automatically captured by the BrowserStack integration during test execution. ```javascript // cypress/e2e/accessibility.cy.js describe('Accessibility Tests', () => { it('should have no accessibility violations on homepage', () => { cy.visit('https://example.com'); // Accessibility violations are automatically captured }); }); ``` -------------------------------- ### Enable Local Testing via CLI Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Initiate local testing directly from the command line using the --local flag. Options for 'local-identifier' and 'local-mode' can also be specified. ```bash browserstack-cypress run --local --local-identifier my-session --local-mode always-on ``` -------------------------------- ### Download BrowserStack Build Artifacts Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Download build artifacts such as videos, screenshots, and logs for a completed build using its build ID. ```bash browserstack-cypress generate-downloads 12345678 ``` -------------------------------- ### Network Log HAR Format Example Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Network logs are captured in the HAR (HTTP Archive) format, providing detailed information about each network request and response, including headers, timing, and content. ```json { "log": { "version": "1.2", "creator": { "name": "WebInspector" }, "entries": [ { "startedDateTime": "2024-01-15T10:30:00.123Z", "time": 245, "request": { "method": "GET", "url": "https://api.example.com/users", "headers": [...] }, "response": { "status": 200, "headers": [...], "content": { "size": 1234 } } } ] } } ``` -------------------------------- ### Initialize a custom-named browserstack.json Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Creates a new BrowserStack Cypress configuration file with a custom name in the current directory. This allows for multiple configurations or non-standard naming. ```bash browserstack-cypress init my-config.json ``` -------------------------------- ### Test Recording via CLI Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Record tests on Cypress Cloud using CLI arguments for record key and project ID. ```bash browserstack-cypress run --record --record-key --projectId ``` -------------------------------- ### CI/CD Platform Detection - BitBucket Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md BrowserStack CLI detects BitBucket CI/CD platform using these environment variables. ```bash BITBUCKET_BUILD_NUMBER=... BITBUCKET_REPO_SLUG=... ``` -------------------------------- ### Test Recording via Environment Variables Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Record tests on Cypress Cloud by setting environment variables for record key and project ID. ```bash export CYPRESS_RECORD_KEY=my_record_key export CYPRESS_PROJECT_ID=my_project_id browserstack-cypress run --record ``` -------------------------------- ### Download Build Artifacts with Custom Credentials Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Download build artifacts using custom BrowserStack username and access key. These override any credentials set in the configuration file or environment variables. ```bash browserstack-cypress generate-downloads 12345678 -u myuser -k mykey ``` -------------------------------- ### Download Build Artifacts from BrowserStack Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Downloads videos, screenshots, and logs for a specified build ID from BrowserStack. Artifacts are saved locally. ```javascript await buildArtifacts.downloadBuildArtifacts(bsConfig, '12345', {}, [], null); console.log('Artifacts downloaded to ./build_artifacts/12345'); ``` -------------------------------- ### Create Build Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md Creates a new test build on BrowserStack. This endpoint is used to initiate a test run with specified configurations. ```APIDOC ## POST /automate/cypress/v1/builds ### Description Creates a new test build on BrowserStack. ### Method POST ### Endpoint /automate/cypress/v1/builds ### Parameters #### Request Body - **devices** (array) - Required - List of target devices and OS combinations. - **test_suite** (string) - Required - S3 path to the test zip file. - **npm_package_suite** (string) - Optional - S3 path to the npm package archive. - **cache_dependencies** (boolean) - Optional - Whether to cache npm dependencies. - **local** (boolean) - Optional - Whether to use a local tunnel. - **localIdentifier** (string) - Optional - Identifier for the local tunnel session. - **project** (string) - Optional - Name of the project. - **customBuildName** (string) - Optional - Custom name for the build. - **parallels** (integer) - Optional - Number of parallel test executions. - **run_settings** (string) - Optional - JSON string of run settings. - **cypress_cli_user_agent** (string) - Optional - User agent string for the CLI. ### Request Example ```json { "devices": ["chrome-Windows10-latest", "firefox-Windows10-latest"], "test_suite": "s3://bucket/tests.zip", "npm_package_suite": "s3://bucket/npm.tar.gz", "cache_dependencies": true, "local": false, "localIdentifier": "session-1", "project": "project-name", "customBuildName": "build-1", "parallels": 5, "run_settings": "{\"headless\":true,...}", "cypress_cli_user_agent": "browserstack-cypress-cli/1.36.8" } ``` ### Response #### Success Response (200) - **status** (string) - The current status of the build. - **build_id** (string) - The unique identifier for the build. - **build_name** (string) - The name of the build. - **project_name** (string) - The name of the project. - **created_at** (string) - Timestamp when the build was created. - **sessions** (array) - List of associated sessions. #### Response Example ```json { "status": "running", "build_id": "12345678", "build_name": "build-1", "project_name": "project-name", "created_at": "2024-01-15T10:30:00Z", "sessions": [] } ``` #### Error Response (400+) - **error** (string) - A general error message. - **message** (string) - A detailed error message. #### Error Response Example ```json { "error": "error message", "message": "detailed error message" } ``` ``` -------------------------------- ### Configure Cypress Cloud Recording Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Record tests to the Cypress Cloud dashboard by exporting your RECORD_KEY and PROJECT_ID, then running the command with the --record flag. ```bash export CYPRESS_RECORD_KEY=your_record_key export CYPRESS_PROJECT_ID=your_project_id browserstack-cypress run --record ``` -------------------------------- ### BuildCapabilities Interface Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/types.md Capabilities sent to the BrowserStack API for build creation. Includes device configurations, test suite details, local testing settings, project information, and run settings. ```typescript interface BuildCapabilities { devices: string[]; // Array of browser-os-version combinations test_suite: string; // URL to uploaded test zip npm_package_suite?: string; // URL to uploaded npm packages cache_dependencies?: boolean; // Local testing local: boolean; localIdentifier?: string; localMode?: string | null; local_mode_inferred?: boolean; local_inferred?: boolean; sync_inferred?: boolean; // Project info project: string; customBuildName: string; // URLs callbackURL?: string; projectNotifyURL?: string; // Test configuration parallels?: number; run_settings: string; // Stringified RunSettings object cypress_cli_user_agent: string; } ``` -------------------------------- ### Basic npm Dependencies Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Specify basic npm dependencies required for your project. ```json "npm_dependencies": { "axios": "^1.15.0", "lodash": "^4.17.21", "moment": "2.29.4" } ``` -------------------------------- ### HostInfo Interface Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/types.md Provides operating system and host information. Utilized for build context and system information reporting. ```typescript interface HostInfo { hostname: string; // Machine hostname platform: string; // Platform string (e.g., 'linux', 'darwin', 'win32') type: string; // OS type (e.g., 'Linux', 'Darwin', 'Windows_NT') version: string; // OS version string arch: string; // Architecture (e.g., 'x64', 'arm64') } ``` -------------------------------- ### Set Custom Build Names with Date/Time Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Create unique build names by appending dynamic date and time information, useful for distinguishing between multiple runs of the same test suite. ```bash browserstack-cypress run -b "Pre-Release-1.0.0-$(date +%Y%m%d-%H%M%S)" ``` -------------------------------- ### Environment Variable Resolution Order - Config File Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md Configuration from a config file (e.g., browserstack.json) has the third priority. ```json { "auth": { "username": "myuser" } } ``` -------------------------------- ### Add Build Tags for Filtering Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Apply tags to your builds using the `--build-tag` flag to easily filter and organize them in the BrowserStack dashboard. Multiple tags can be comma-separated. ```bash browserstack-cypress run --build-tag "smoke-tests,daily-run" ``` -------------------------------- ### Configure npm Dependency Caching Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Enable npm dependency caching and specify dependencies to be cached within the run_settings. This speeds up build startup and reduces upload time on subsequent runs. ```json { "run_settings": { "cache_dependencies": true, "npm_dependencies": { "axios": "^1.15.0", "lodash": "^4.17.21" } } } ``` -------------------------------- ### Override Credentials and Build Name Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Provide custom username, access key, and build name directly via command-line arguments, overriding any values set in the configuration file. This is useful for dynamic configuration in different environments. ```bash browserstack-cypress run -u myusername -k myaccesskey -b "my-build-#1" ``` -------------------------------- ### write Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Writes data to a file based on the provided configuration and arguments. ```APIDOC ## write(config, args, bsConfig, callback) ### Description Writes data to a file. ### Parameters - `config` (object) - Required - Configuration object. - `args` (object) - Required - CLI arguments. - `bsConfig` (BrowserStackConfig) - Required - BrowserStackConfig object. - `callback` (function) - Required - A callback function. ### Returns void ### Example ```javascript fileHelpers.write(config, args, bsConfig, () => { console.log('File written'); }); ``` ``` -------------------------------- ### capabilityHelper.js - Capability Generation and Validation Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Handles the generation of BrowserStack capabilities and validation of configuration settings. It provides functions to create the capabilities object based on configuration and uploaded artifacts, and to validate these configurations against a set of predefined rules. ```APIDOC ## capabilityHelper.js - Capability Generation and Validation ### Description Build capability generation and configuration validation. This module provides functions to generate the capabilities object required for BrowserStack sessions and to validate the provided configuration settings against a set of rules to ensure a successful test run. ### Functions #### `caps(bsConfig, zip)` - **Description**: Generates capabilities object from browserstack.json and uploaded zip URLs. - **Parameters**: - `bsConfig` (BrowserStackConfig) - BrowserStackConfig object. - `zip` (object) - Object with `zip_url` and `npm_package_url` strings. - **Returns**: Promise - Promise resolving to JSON string of capabilities. - **Example**: ```javascript const caps = await capabilityHelper.caps(bsConfig, { zip_url: 's3://bucket/tests.zip', npm_package_url: 's3://bucket/npm.tar.gz' }); ``` #### `validate(bsConfig, args)` - **Description**: Validates configuration against rules. - **Parameters**: - `bsConfig` (BrowserStackConfig) - BrowserStackConfig object. - `args` (object) - CLI arguments. - **Returns**: Promise - Promise that resolves on success, rejects with error message. - **Validation Checks**: - Authentication params present - Browser list not empty - Test suite not empty - Parallels is positive integer - Spec timeout in range (1-120) - Local mode is valid - Base URL matches local setting - No conflicting settings - **Example**: ```javascript await capabilityHelper.validate(bsConfig, {}); ``` ``` -------------------------------- ### Configure Localhost Testing with Cypress Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Set up local testing to target applications running on localhost. This involves enabling local testing in 'browserstack.json' and configuring 'baseUrl' in 'cypress.json'. ```json { "run_settings": { "cypress_config_file": "./cypress.json" }, "connection_settings": { "local": true } } ``` ```json { "baseUrl": "http://localhost:3000", "e2e": { "specPattern": "cypress/e2e/**/*.cy.js" } } ``` ```bash # Start local app npm start & # Run tests with local testing browserstack-cypress run ``` -------------------------------- ### Generate BrowserStack Build Report Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Generate an HTML test report for a completed build using its build ID. Custom credentials can be provided. ```bash browserstack-cypress generate-report 12345678 ``` ```bash browserstack-cypress generate-report 12345678 -u myuser -k mykey ``` -------------------------------- ### Create Build Endpoint Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md The POST endpoint for creating a new test build on BrowserStack. ```http POST /automate/cypress/v1/builds ``` -------------------------------- ### upload Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Uploads a zip file containing test artifacts to BrowserStack. It returns a URL and MD5 checksum for the uploaded file. ```APIDOC ## upload(filePath, bsConfig) ### Description Upload test zip file to BrowserStack. ### Parameters - `filePath` (string) - Required - Path to zip file - `bsConfig` (BrowserStackConfig) - Required - BrowserStackConfig object ### Returns Promise<{ zip_url: string, md5_checksum: string }> ### Example ```javascript const result = await zipUpload.upload('./tests.zip', bsConfig); console.log(`Uploaded to ${result.zip_url}`); ``` ``` -------------------------------- ### Configure 'always-on' Local Testing Mode Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Set 'local_mode' to 'always-on' for a persistent local connection throughout the build. This mode is recommended for most scenarios, especially in CI/CD pipelines, due to its stability and performance. ```json { "connection_settings": { "local": true, "local_mode": "always-on" } } ``` -------------------------------- ### Download Network Logs Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Download captured network logs along with other artifacts by using the 'generate-downloads' command with your build ID. Logs will be located in the 'logs/' directory of the downloaded zip file. ```bash browserstack-cypress generate-downloads ``` -------------------------------- ### LocalTestingConfig Interface for BrowserStack Local Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/types.md Configuration interface for the BrowserStack Local binary. Includes access key, parallel run settings, host patterns, and logging options. ```typescript interface LocalTestingConfig { key: string; // BrowserStack access key parallelRuns?: number; folder?: string; hosts?: Array<{ name: string; // Hostname pattern port: number; // Port number }>; logFile?: string; logLevel?: string; // 'info' | 'debug' | 'error' verbose?: boolean; onlyAutomate?: boolean; } ``` -------------------------------- ### downloadBuildArtifacts Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/modules.md Downloads build artifacts such as videos, screenshots, and logs from a specified BrowserStack build. ```APIDOC ## downloadBuildArtifacts(bsConfig, buildId, args, rawArgs, buildReportData) ### Description Download videos, screenshots, and logs from completed build. ### Parameters - `bsConfig` (BrowserStackConfig) - Required - BrowserStackConfig object - `buildId` (string) - Required - Build ID to download artifacts for - `args` (object) - Required - CLI arguments - `rawArgs` (array) - Required - Raw command line arguments - `buildReportData` (object) - Required - Build report data for analytics ### Returns Promise ### Artifacts Structure: ``` build_artifacts/ └── / ├── / │ ├── / │ │ ├── videos/ │ │ ├── screenshots/ │ │ └── logs/ ``` ### Example ```javascript await buildArtifacts.downloadBuildArtifacts(bsConfig, '12345', {}, [], null); console.log('Artifacts downloaded to ./build_artifacts/12345'); ``` ``` -------------------------------- ### Configure Custom JSON Reporter Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Use the `--reporter` and `--reporter-options` flags to specify a JSON reporter and its output file. This is useful for parsing test results programmatically. ```bash browserstack-cypress run \ --reporter json \ --reporter-options "outputFile=test-results.json" ``` -------------------------------- ### Enable Local Testing for Cypress Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/cli-commands.md Run Cypress tests against a local development environment by enabling the `--local` flag. Use `--local-identifier` to uniquely name your local testing session. ```bash browserstack-cypress run --local --local-identifier my-test-session ``` -------------------------------- ### Configure 'on-demand' Local Testing Mode Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Set 'local_mode' to 'on-demand' to establish a local connection per test. This mode is suitable for scenarios requiring lower resource usage and better isolation between tests. ```json { "connection_settings": { "local": true, "local_mode": "on-demand" } } ``` -------------------------------- ### Test Recording Configuration Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/configuration.md Configure settings to record tests on Cypress Cloud. ```json "run_settings": { "project_name": "my-project" } ``` -------------------------------- ### Set Project Name Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md Override the project name for your tests. Default is from config file or 'project-name'. ```bash export BROWSERSTACK_PROJECT_NAME="My Project" browserstack-cypress run ``` -------------------------------- ### BrowserConfiguration Interface Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/types.md Defines a single browser/OS combination for test execution. Specify the browser, OS, version(s), and optional per-browser accessibility settings. ```typescript interface BrowserConfiguration { browser: string; // 'chrome' | 'firefox' | 'edge' | 'safari' os: string; // 'Windows 10' | 'Windows 11' | 'OS X Monterey' | etc. versions: string[]; // ['latest', 'latest-1', '120.0', etc.] accessibility?: boolean; // Optional per-browser accessibility setting } ``` -------------------------------- ### Create Build Success Response Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/api-endpoints.md A successful response (HTTP 200) when creating a build, indicating the build status, ID, name, and project. ```json { "status": "running", "build_id": "12345678", "build_name": "build-1", "project_name": "project-name", "created_at": "2024-01-15T10:30:00Z", "sessions": [] } ``` -------------------------------- ### CI/CD Platform Detection - GitLab CI Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md BrowserStack CLI detects GitLab CI/CD platform using these environment variables. ```bash GITLAB_CI=true CI_PROJECT_NAME=... CI_JOB_ID=... CI_COMMIT_BRANCH=... ``` -------------------------------- ### Enable BrowserStack Automation Mode Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md Set BROWSERSTACK_AUTOMATION to true to enable automation mode, typically used for CI/CD integration. ```bash export BROWSERSTACK_AUTOMATION=true browserstack-cypress run ``` -------------------------------- ### Enable Debug Logs for Local Connection Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Enable detailed debug logs for the local connection by setting the BROWSERSTACK_LOCAL_DEBUG environment variable to true. This is useful for troubleshooting connection issues. ```bash export BROWSERSTACK_LOCAL_DEBUG=true browserstack-cypress run --local ``` -------------------------------- ### Enable Local Testing in browserstack.json Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Configure local testing by setting 'local' to true and optionally providing a 'local_identifier' and 'local_mode'. This enables testing against private or staging environments. ```json { "connection_settings": { "local": true, "local_identifier": "my-local-session", "local_mode": "always-on" } } ``` -------------------------------- ### Submit Builds Asynchronously Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/advanced-features.md Submit builds asynchronously using the `--async` flag to prevent CI/CD timeouts. The `build_id` is returned, allowing you to poll for status later. ```bash BUILD_ID=$(browserstack-cypress run --async | jq -r '.build_id') echo "Build submitted with ID: $BUILD_ID" ``` -------------------------------- ### CI/CD Platform Detection - GitHub Actions Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/_autodocs/environment-variables.md BrowserStack CLI detects GitHub Actions CI/CD platform using these environment variables. ```bash GITHUB_ACTIONS=true GITHUB_REPOSITORY=... GITHUB_RUN_ID=... GITHUB_REF=... ``` -------------------------------- ### Run Cypress Tests on BrowserStack Source: https://github.com/browserstack/browserstack-cypress-cli/blob/master/README.md Execute your Cypress tests on BrowserStack using the CLI. Ensure your browserstack.json is configured correctly before running this command. ```bash $ browserstack-cypress run ```