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 inpackage.json.- CI config files (like
.github/workflows/ci.ymlor.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 runfor headless test execution. - Cache
node_modulesor~/.npmto 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.