0
0
CypressHow-ToBeginner ยท 4 min read

How to Run Cypress Tests in CI/CD Pipelines

To run Cypress in a CI/CD pipeline, install Cypress in your project, add a test script in package.json, and configure your CI tool to run npm run test or npx cypress run. Ensure the CI environment has necessary dependencies and browsers installed or use Cypress Docker images for smooth execution.
๐Ÿ“

Syntax

Use the following command to run Cypress tests in CI/CD environments:

  • npx cypress run: Runs all Cypress tests headlessly.
  • npm run test: Runs the test script defined in package.json.
  • CI config files (like .github/workflows/ci.yml or .gitlab-ci.yml) specify steps to install dependencies and run tests.
bash
npm install cypress --save-dev

# Add this script to package.json
"scripts": {
  "test": "cypress run"
}

# Run tests in CI
npx cypress run
๐Ÿ’ป

Example

This example shows a GitHub Actions workflow that installs dependencies, caches Cypress, and runs tests headlessly.

yaml
name: Cypress CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Use Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 18
      - name: Cache node modules
        uses: actions/cache@v3
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-
      - name: Install dependencies
        run: npm ci
      - name: Run Cypress tests
        run: npm run test
Output
Run Cypress tests headlessly in CI and report pass/fail status
โš ๏ธ

Common Pitfalls

Common mistakes when running Cypress in CI/CD include:

  • Not installing dependencies before running tests.
  • Running tests without a display server or browser in headless mode.
  • Ignoring caching which slows down builds.
  • Not setting environment variables needed for tests.

Always use cypress run for CI, not cypress open, which requires a GUI.

bash
Wrong:
  run: cypress open

Right:
  run: npx cypress run --headless
๐Ÿ“Š

Quick Reference

Summary tips for running Cypress in CI/CD:

  • Use npx cypress run for headless test execution.
  • Cache node_modules or ~/.npm to speed up builds.
  • Use official Cypress Docker images if environment setup is complex.
  • Configure CI to fail the build on test failures.
  • Set environment variables securely in CI settings.
โœ…

Key Takeaways

Install Cypress and add a test script to run tests headlessly in CI.
Configure your CI pipeline to install dependencies and run npx cypress run.
Use caching and official Docker images to optimize CI runs.
Avoid using cypress open in CI as it requires a GUI.
Ensure environment variables and dependencies are properly set in CI.