App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide Cypress Automation Tutorial

Cypress Automation Tutorial

By Ganesh Hegde, Community Contributor -

Test Automation is a way of verifying and validating test scenarios via specific tools and frameworks. QAs create automated scripts, feed them into automation tools that launch the application, run through the test scenario, and mark the test as passed or failed.

Test Automation is recommended for repetitive scenarios since it saves time and effort that would otherwise have to be put in by human testers.

Why is Test Automation Important?

  • Helps implement modern DevOps principles by injecting speed into the development pipeline. 
  • It reduces human error since machines do not make mistakes if they have the right input. 
  • Provides faster results. 
  • Allows for multiple tests to be run simultaneously through parallel testing.

What is Cypress Framework?

Cypress framework is a NodeJS-based modern automation tool that supports JavaScript/Typescript as the programing language. There are many advantages and disadvantages of Cypress. However, despite its recency, it is the most popular and easy-to-use tool in the automation world, quickly becoming a favorite of devs and testers. 

Cypress Installation Guide

Prerequisites:

Here is the detailed installation guide for Cypress.

How to Set up Cypress for Automation

Cypress is shipped as an NPM package, so install the npm package from the repository and configure it to use Cypress.

Step 1: Navigate to the desired folder. Create New Folder (cypressdemo).

Step 2: Inside the cypressdemo folder, open terminal or command prompt.

Step 3: Enter the command:  npm install cypress –save-dev

Step 4: Once the installation is complete, enter the command: npx cypress open

The npx cypress open command prepares Cypress for the first time and launches the Cypress test runners where we can see example tests and play around with them.

Understanding Folder Structures in Cypress

By default, Cypress comes with a folder structure. The main folder is cypress, within which there are subfolders.

  • Integration: This folder contains the actual test scripts.
  • Fixtures: If you are using external data inside your tests, your data can be organized inside the Fixtures folder.
  • Plugins: The Plugins folder contains the special files that can execute the code before the project loads. If your project needs pre-processors, include them in this folder and configure them accordingly. By default, the plugins folder contains the index.js file, which can be customized to create your tasks.
  • Support: The Support folder contains utilities, global commands, frequently used codes, etc. By default, this folder comes with two files – commands.js and index.js. Additional files and folders can be added as required.
  • Assets: A folder called downloads will be created after the test run, including screenshots, videos, etc.

Writing your First Test Case for Cypress Automation

The cypressdemo folder contains 

  1. node_modules folder
  2. cypress folder
  3. cypress.json file
  4. package.json file
  5. package-lock.json file.

To create your tests, navigate to cypress/integration and create a fresh new folder (eg: demo).

Inside the demo folder, create the test file (ex: firsttest.js) using the code below:

//firsttest.js

describe('My First Test', () => {

    it('Launch Browser and Navigate', () => {

        cy.visit('https://www.browserstack.com/');

        cy.title().should('eq', 'Most Reliable App & Cross Browser Testing Platform | BrowserStack')

    })

  })

 

Running First Automated Test with Cypress

BrowserStack allows you to run Cypress tests on the latest browsers. Get 30+ versions across Windows and macOS, with more to come. You can also run hundreds of Cypress tests in parallel without maintaining countless Docker images. It takes a few easy steps to start running Cypress tests on BrowserStack.

Run Cypress Tests on Real Browsers

Cypress Tests can be executed in two ways:

  1. Using Cypress Runner (UI)
  2. Using Cypress CLI (Command Line)

1. Execute Cypress Tests Using Cypress Test Runner

From your Visual Studio Code Terminal or Command-Line, run the command st the project folder level (cypressdemo).

npx cypress open

The command above opens the Cypress Test Runner. Choose the newly created test file.

Click on the firsttest.js file under the demo folder to execute tests.

Cypress automation tutorial

Test Result

Cypress automation tutorial

2. Running Cypress Tests Using Command Line

Syntax:

npx cypress run [--spec <path_to_spec_file]

Run firsttest.js using the command below:

npx cypress run --spec "./cypress/integration/demo/firsttest.js"

The command above executes tests in headless mode, so we will not see any browser launches or execution of tests, all of which happens in the background.

Cypress CLI Execution Result

Cypress Command Line Report

Best Practices for Cypress Automation

  1. Create Independent Tests: Isolate the tests as much as possible. Don’t create tests dependent on each other.
  2. Authenticate applications programmatically: Authentication or Logging into your application should be handled programmatically (Example: Using API calls), reducing testing dependency.
  3. data-* attributes: Adding attributes to UI elements such as data-test, data-testid, or data-cy increases application testability and reduces dependency on selectors making the test stable.
  4. Utilize Cypress Architecture for easy and stable tests.
//Avoid

const myBtn = cy.contains('button', 'Click Me')

myBtn.click()

//Use

cy.contains('button', 'Click Me').as('myBtn')

cy.get('@myBtn').click()

           5. Avoid using the after and afterEach hooks: There are chances that code inside the after and afterEach hooks may not execute as expected. In that case, Cypress may halt test execution and not execute remaining tests.

          6. Avoid using cy.wait(): cy.wait() may slow down your test execution. Instead, rely on default wait mechanisms.

cy.intercept(...).as('req')

...

cy.wait('@req') 

           7. Do not start your web server using cy.task() or cy.exec(): Before test execution starts ensure your application is up and running.
           8. cypress.json is a cypress configuration file. Set the correct baseURL inside the configuration file and/or create multiple configuration files as per the environment. You can also use the environment variable to execute tests as per the required environment.

Tips and Tricks for an efficient Cypress Automation Testing

1. Use cypress.json file to configure baseUrl, browser type, etc.

2. Cypress captures videos and screenshots for tests which can be disabled using cypress.json entries.

"video": false,

"screenshotOnRunFailure":false

3. Create Shortcut command for executing your tests. Add entries to package.json scripts.

Example:

"scripts": {"test" : "cypress run --spec './cypress/integration/demo/firsttest.js'"},

4. You can override the default timeout settings as per requirements.

5. In the Cypress Test Runner UI, navigate to Settings, to view all configurations.

How to execute Cypress Test Automation Using BrowserStack

Step 1: Install BrowserStack CLI using npm install -g BrowserStack-cypress-cli

Step 2: Configure Browserstack CLI using npx browserstack-cypress init

Step 3: The command above creates browserstack.json in your Project Directory. Enter the fields:

  • auth – specify your username and access key. Learn about different auth options.
  • browsers – change the list of browsers and OS if you want to
  • run_settings – specify the cypress_config_file, parallels, npm_dependencies, and any other options that you want to change

Step 4:  Run Your Cypress Tests on BrowserStack using npx browserstack-cypress run –sync

Use BrowserStack’s real browsers to ensure that all tests return 100% accurate results, even when executing multiple tests simultaneously. Don’t limit your tests to the various inadequacies of emulators and simulators; only rely on the real deal to create customer-ready, meticulously optimized web applications. 

Run Cypress Tests on Real Browsers

Cypress Automation Tutorial

Tags
Automation Testing Cypress

Featured Articles

Cypress End to End Testing: Tutorial

Cross Browser Testing with Cypress : Tutorial

App & Browser Testing Made Easy

Seamlessly test across 20,000+ real devices with BrowserStack

BrowserStack Logo Run Cypress Tests on 30+ Real Browser Versions Contact us Get Started Free