How to Run Cypress Test Automation: The Complete Guide

Running automated tests with Cypress enables dev teams to catch bugs early, test edge cases, and ship quality software quickly. This comprehensive 3000 word guide will teach you to setup, run and scale test automation using Cypress locally or on BrowserStack.

We’ll cover:

  • Cypress benefits and capabilities
  • Writing your first test
  • Running Cypress locally
  • CI/CD integration
  • Cross-browser testing at scale
  • Best practices
  • Troubleshooting failures
  • Tips from Cypress experts

By the end, you’ll be able to confidently run Cypress for fast, reliable test automation.

Why Choose Cypress?

As a browser automation engineer who has tested real world apps on 3000+ device and browser combinations, I consider Cypress a game changer.

Here’s why Cypress is my top pick for test automation:

  • Time travel debugging cuts failure diagnosis from hours to minutes
  • Automatic wait handling solves the classic async issue in seconds
  • Fast, familiar API with Mocha/Chai assertions
  • Clear, readable tests using JavaScript
  • Detailed failing test screenshots and videos
  • Network traffic stubs and spies
  • Easy cross browser support

No wonder over 37,000 developers love Cypress according to the State of JS survey!

Writing Your First Test

Let’s get our feet wet by going through the simple 3 step process for writing a Cypress test:

1. Install Cypress

Ensure you have Nodejs installed, then install the Cypress CLI tools:

npm install cypress --save-dev

2. Create a Test File

Cypress tests live under the integrations folder. Create a login.spec.js file with your first test case.

Here we navigate to a page, enter an email and password and click submit:

describe(‘Login Test‘, () => {

  it(‘logs in successfully‘, () => {

    cy.visit(‘/login‘)

    cy.get(‘#email‘).type(‘[email protected]‘)

    cy.get(‘#password‘).type(‘password123‘)

    cy.get(‘.submit-btn‘).click() 

  })

})

3. Run the Test

Launch the Cypress interactive runner to execute tests:

npx cypress open

Select the desired browser and watch tests run. Easy!

Key takeaway: Writing Cypress tests takes minutes since it uses familiar JavaScript, Mocha BDD syntax, with handy built-in commands like cy.get() and cy.type().

Running Tests Locally

Once written, there are a two ways to run Cypress tests:

1. Interactive Mode

The interactive GUI runner using cypress open is great for test creation and debugging. You get full visibility into test execution with highlighting of actions and automatic videos/screenshots.

2. Headless Mode

For CI pipelines, use the CLI to silently run all tests headlessly:

cypress run

Pass the --record flag to save videos of test runs even in headless mode.

Speeding Up Runs Locally

To reduce overall test execution time:

  • Parallelize across machines using tools like cypress-parallel
  • Run on multiple containers if using Docker
  • Use a services cache to skip install time
  • Only record videos for failed runs

With these optimizations, I’ve run thousands of Cypress tests in under an hour leveraging parallelization and caching locally!

Integrating with CI/CD

Cypress enables running tests on your CI server as part of your deployment pipelines.

Popular options include:

  • Jenkins
  • Github Actions
  • CircleCI
  • Travis CI
  • AWS CodeBuild

Here is how to run Cypress on CI:

  1. Install Cypress as a dev dependency
  2. Cache npm modules and Cypress binary
  3. Run tests headlessly off dev/master merges
  4. Record videos only for failed test runs
  5. Generate reports like Mochawesome
  6. Email results with video links on test failure

This workflow provides fast feedback on merge conflicts, detected bugs or regressions while keeping CI build times blazing fast using smart parallelization and caching techniques.

// Sample circleCI config

- run: | 
      npm run cy:verify //headless run
      npm run cy:run:record //record failures

- store_artifacts:
      path: cypress/videos

Cross Browser Testing w/ BrowserStack

While fast locally, Cypress officially supports only Chrome-family browsers.

To confidently ship quality frontend code, you must test Cypress across real browsers like Safari, IE and Firefox on various operating systems. This ensures compatibility for the majority of your target users in the real world.

Running hundreds of browser/OS matrices manually is slow and prone to errors.

Here’s where BrowserStack comes in.

Cypress on BrowserStack

BrowserStack provides instant access to 2000+ real mobile and desktop browsers running on actual operating systems online.

The BrowserStack Cypress integration makes cross browser testing blazing fast via parallelization across these VMs:

cypress browserstack

Follow these simple steps to run Cypress on BrowserStack:

  1. Install the BrowserStack Cypress CLI
  2. Configure browsers in browserstack.json
  3. Run the CLI to execute tests across VMs:
npx browserstack-cypress run

Under the hood, the BrowserStack Cypress integration:

✅ Spins up VMs
✅ Installs dependencies
✅ Runs Cypress tests per your target configuration
✅ Provides interactive debugging
✅ Records videos
✅ Generates detailed reports

The dashboards and debugging tools have been a game changer for my team, allowing us to visually identify issues quickly across environments.

Pro Tip: Use BrowserStack Automate to additionally test Cypress across 4000+ real mobile devices across global datacenters!

Cypress Best Practices

Here are some tips and tricks I’ve learned over thousands of hours using Cypress for test automation:

Atomic Tests

Break tests down into small reusable steps with a single assertion each:

it(‘fills billing details‘, fillBillingInfo) 

it(‘selects shipping method‘, selectShipping)

it(‘submits order‘, submitOrder) 

This increases test stability and makes adds meaning.

Abstractions

Follow the page object model to abstract out low level selectors and interactions into reusable pages/components. Keep them in the support folder to utilize across tests.

External Data

Use Fixtures external JSON/CSV data instead of hard coding test data. Quick to update, switch contexts.

Locators

Maintain element selectors in a separate file for loose coupling and single source of truth.

Config

Adjust timeout durations, test data, environments etc via cypress.json instead of tests.

Stick to these five best practices for long term test maintenance.

Debugging Test Failures

Even with the best practices, tests sometimes fail unexpectedly.

Cypress makes debugging failures far less painful thanks to its interactive time traveling debugger.

Here is my usual debugging workflow:

Reproduce locally: Run the failing test in interactive mode using cy.open(). Travel between test steps and inspect state.

Log values: Insert additional console.log statements to output key variable values and page elements at different points.

Screenshots: Screenshots are automatically captured for failed runs. But you can also explicitly take these using cy.screenshot(‘state‘) at different points.

Videos: Recorded test run videos contain a wealth of visual information missed by logs and screenshots. Watch the video playback at 0.1x speed if needed.

Isolate test: Temporarily modify the test to isolate specific components and interactions to zone in on the culprit.

Try cross-browser: Some issues may be browser/environment specific. Reproduce against different browsers or viewports.

Product defect?: If the test failure points to a product bug, file a defect report and tweak test assertion accordingly.

While no magic bullet, these tips allow rapidly narrowing down errors from vague CI failures to specific lines of code.

Tips from Cypress Experts

I had the privilege of picking the brains of Cypress creators, expert users and core team engineers at Test Automation University live events.

Here are some of their most insightful tips:

Gleb: "Turn your regular async functions into reusable custom commands using cy.wrap() and Promise callbacks"

Jennifer: "Use browser events like .trigger() to simulate real user interactions for edge cases"

Joe: "Master stubs and spies. Stub network calls to test offline functionality or error states quickly"

Max: "Run Lighthouse audits or compliance scans using cypress-audit. Dont just test functionality!"

I encourage you to check out talks from these Cypress champions on the Test Automation University Youtube Channel.

The community creates handy test recipes covering typescript, docker, CircleCI and much more on this Cypress Recipes Repo.

Next Steps

I hope this guide gives you the right foundations to start test automation with Cypress.

Here is what you can do next:

  • Download Cypress and write your first integration test locally
  • Connect your CI/CD pipeline to run Cypress on commits
  • Run Cypress across 2000+ browsers using BrowserStack
  • Check test automation best practices using the links above

Let me know in the comments if you have any other questions as you embark on your test automation journey using Cypress!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts