Cypress Automation Testing Tutorial: E2E Testing with Cypress
Published: 2022-11-09 09:54:22

The demand for Cypress automation testing has increased exponentially with the need to deliver products faster to the market. As per the State of JS survey 2021, Cypress awareness has climbed from 74% in 2020 to 83% in 2021 with 92% satisfaction. Cypress has emerged as a prominent tool for web automation testing in recent years addressing fundamental issues faced by modern web applications. Now Selenium testing has been widely accepted for web [automation testing](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog). Which often triggers a debate around [Selenium vs Cypress](https://www.lambdatest.com/blog/cypress-vs-selenium-comparison/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog), however, this article isn’t just about resolving the Selenium vs Cypress debate. This is going to be on help you perform Cypress automation testing like a pro.

In this [Cypress tutorial](https://www.lambdatest.com/learning-hub/cypress-tutorial?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog), we talk about the Cypress test automation framework that is fundamentally and architecturally different from the [Selenium test automation](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog). How to set up and install Cypress and finally, run Cypress automation testing over hundreds of browsers and operating systems using the LambdaTest [Cypress cloud](https://www.lambdatest.com/cypress-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog).

{% youtube jX3v3N6oN5M %}

## Introduction To Cypress Automation Testing Framework

Cypress is a purely JavaScript-based front-end testing framework that lets you easily write powerful and flexible tests for your web applications. It enables advanced testing options for both unit tests and integration tests with benefits such as easy test configuration, convenient reporting, intuitive dashboard experience, and more.

As Cypress supports only JavaScript, it is widely accepted by the developer community. It also has a huge following (around 32K GitHub stars) from developers and QA engineers since the time was publicly released for the community.

So why Cypress automation is considered an alternative to Selenium?

Let’s take a look at the architectural differences between Cypress and Selenium and how Cypress is resolving the problems faced in modern-day web application testing.

Get the best out of your Cypress tests with LambdaTest’s online [Cypress automation tool](https://www.lambdatest.com/cypress-automation-tool?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog). Check out how you can execute your Cypress test scripts using LambdaTest’s online cloud.

***Online mobile [emulators online](https://www.lambdatest.com/mobile-emulator-online?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=) from LambdaTest allows you to seamlessly test your mobile applications, websites,and web apps on mobile browsers and mobile devices.***

## Understanding Selenium Architecture

[Selenium WebDriver](https://www.lambdatest.com/blog/selenium-webdriver-tutorial-with-examples/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) is a powerful tool for developers that lets you perform automation tests across different browsers. This architecture includes a Selenium server that runs your tests, browser driver corresponding to the browser (under test), and ’N’ number of clients that communicate with the server, typically in the language supported by the Selenium framework.

Shown below is the top-level architecture diagram of the Selenium 3 framework:

![](https://cdn-images-1.medium.com/max/2048/0*mj5h8yKqUPDY0tYj.png)



As of writing this blog, Selenium 4 is in the beta stage and open to use for the community. [Selenium 4 is W3C compliant](https://www.lambdatest.com/blog/selenium4-w3c-webdriver-protocol/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) which means that test flakiness will be significantly reduced with Selenium 4. A couple of features of Selenium 3 are deprecated in Selenium 4, you can make sure to check [what is new in Selenium 4 and what is deprecated in it](https://www.lambdatest.com/blog/what-is-deprecated-in-selenium4/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog).

Now, let’s dive into Cypress architecture and its breakthrough features to understand the difference with Selenium.

## Understanding Cypress Architecture

Cypress is an open-source [testing framework based on JavaScript](https://www.lambdatest.com/blog/top-javascript-automation-testing-framework/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) that supports web application testing. Unlike Selenium, Cypress automation testing works completely on a real browser without the need for driver binaries. The automated code and application code share the same platform, which gives complete control over the application under test.

To describe the backend story of Cypress test automation, let’s have a look at its high-level architecture.

![](https://cdn-images-1.medium.com/max/2000/0*qKfORTDkTEM3ynWM.jpg)

[Cypress automation](https://www.lambdatest.com/blog/cypress-test-automation-framework/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) testing runs on NodeJS server, which communicates with the test runner(Browser) instrumentalized by Cypress to run the application (one of the iframe) and test code(another iframe) in the same event loop.

Here’s quick video if you have doubts regarding how to handle iframes in Cypress.

{% youtube D3jw8-eRzjs %}


This in turn allows the Cypress automation testing code to mock and even change the JavaScript object on the fly. This is one of the primary reasons why Cypress automation testing is expected to execute faster than corresponding Selenium test automation.

Watch this video to learn how Cypress can be used to automate accessibility testing.

{% youtube gRHwcIVDr8U %}

**Key benefits of using Cypress test automation framework:**

* Cypress is easy to set up.

* Cypress has an in-built wait for requests feature that eliminates the need to configure additional waits.

* There is no need for driver binaries in Cypress automation testing and execution happens on the real browser.

* Since test code and application run in the same browser, it can access application JS objects.

* Cypress automation testing lets you change code and execute the same on the fly .

* It provides dashboard support for detailed reporting.

* It supports parallel test execution.

* It has support for BDD and TDD style testing.

* Cypress tests are less flaky due to the auto-wait features supported by the framework.

* At each step, screen grabs that show the test behavior are captured. These can be super helpful in debugging issues with the tests.

* Detailed documentation and thriving community.

***This [smoke testing](https://www.lambdatest.com/learning-hub/smoke-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=learning_hub) tutorial covers what smoke testing is, its importance, benefits, and how to perform it with real-time examples.***

## Setting Up Cypress Automation Testing

Cypress requires Node JS (>= 12) to be pre-installed on the machine. It is bundled into a singleton package which can be added to your node_modules with npm or yarn using the following commands:

npm install cypress

OR

yard add cypress.

**Note:** Make sure you have initialized your folder with npm init or package.json file is created under your project folder.

Once Cypress packages are added to your project directory, you should be able to see the cypress folder added to your project with pre-added tests for sample testing.

**Cypress Test runner**

To open Cypress test runner and view the pre-added tests, run the following command on the terminal:

**npx cypress open**

If you manage commands through package.json, then you might write it under scripts that would look something as shown below. In that case, use the following command:

**npm run cy:open**

    {
    ...
    "scripts":{
    "cy:open":"cypress open",
    ...
    }
    ...
    }

Once you execute the command, the test runner would show up as seen below:

![](https://cdn-images-1.medium.com/max/2048/0*3Beedsp0HCRSpQjW.png)

As in the above screenshot, you can choose to run the specific test by selecting one or run all at the root folder. You can also run the tests by selecting a browser via CLI:

npx cypress run -- --browser chrome

Additionally, to run specific file use:

npx cypress run -- --browser chrome --spec ''

**Sample Code**

actions.spec.js file is written with Mocha style and uses Cypress built-in commands to launch and interact with the browser. If you’re new to Mocha, you can refer to this [Mocha tutorial](https://www.lambdatest.com/blog/mocha-javascript-tutorial-with-examples-for-selenium-testing/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog).

{% youtube hUDQOcabs0Y %}

List of a few commands that we would be using is shown below:

* cy.visit() — Launch a browser with the URL provided as the argument

* cy.get() — Get the elements using CSS-selectors

* type()- Enter the value in input boxes

* {keyCommand} like “{enter}” — Write keyboard actions

* Asserts command — Cypress automation testing uses its own BDD style of assertions inspired by likes of Chai

There are a whole bunch of advanced commands around Cypress API, which you can check on the Cypress official website.

For demonstration of Cypress test automation, we use the Kitchen Sink example which is available on the official GitHub of Cypress.

    describe('Actions', () =&gt; {
      beforeEach(() =&gt; {
        cy.visit('[https://example.cypress.io/commands/actions'](https://example.cypress.io/commands/actions'))
      })
     
      // [https://on.cypress.io/interacting-with-elements](https://on.cypress.io/interacting-with-elements)
     
      it('.type() - type into a DOM element', () =&gt; {
        // [https://on.cypress.io/type](https://on.cypress.io/type)
        cy.get('.action-email')
          .type('[fake@email.com](mailto:fake@email.com)').should('have.value', '[fake@email.com](mailto:fake@email.com)')
     
          // .type() with special character sequences
          .type('{leftarrow}{rightarrow}{uparrow}{downarrow}')
          .type('{del}{selectall}{backspace}')
     
          // .type() with key modifiers
          .type('{alt}{option}') //these are equivalent
          .type('{ctrl}{control}') //these are equivalent
          .type('{meta}{command}{cmd}') //these are equivalent
          .type('{shift}')
     
          // Delay each keypress by 0.1 sec
          .type('[slow.typing@email.com](mailto:slow.typing@email.com)', { delay: 100 })
          .should('have.value', '[slow.typing@email.com](mailto:slow.typing@email.com)')
     
        cy.get('.action-disabled')
          // Ignore error checking prior to type
          // like whether the input is visible or disabled
          .type('disabled error checking', { force: true })
          .should('have.value', 'disabled error checking')
      })
     
      it('.focus() - focus on a DOM element', () =&gt; {
        // [https://on.cypress.io/focus](https://on.cypress.io/focus)
        cy.get('.action-focus').focus()
          .should('have.class', 'focus')
          .prev().should('have.attr', 'style', 'color: orange;')
      })
        
    }

Here is the execution snapshot of the test running on the Chrome browser:

![](https://cdn-images-1.medium.com/max/2048/0*NBRMM_3xKQhde-ye.png)

Defaults to Spec reporter in the console output:

![](https://cdn-images-1.medium.com/max/2048/0*nLByZDfVJ9h1c7fj.png)

The amazing part to notice about execution is that it auto records your test execution and stores it as a .mp4 file for viewing or sharing with other members in the team.

**Dashboard services of Cypress test automation framework**

While test runner does a wonderful job of running tests and storing the recorded session for execution, Cypress automation testing provides more amazing features through its paid services. The paid services are completely optional for use but CI integration and parallelization of test runs stand out from the rest.

**Some of the key features of dashboard services include:**

* Allows tests to run parallel with CI setup.

* Allows tests to be grouped and run for multilevel environments or browsers.

* Easily integrates with CI tools.

* Provides insights into your historical runs.

* Auto balancing feature to reduce the load on CI servers.

**Configuring test to run in the dashboard**

For running tests in Dashboard services, we need to create an account on [Cypress Dashboard](https://dashboard.cypress.io/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog). Follow the below steps for creating a projectId and record key.

![](https://cdn-images-1.medium.com/max/2048/0*8Sl1jwg1Z3EYL3qd.png)

![](https://cdn-images-1.medium.com/max/2048/0*G0uDeEa56ifkpep0.png)

![](https://cdn-images-1.medium.com/max/2048/0*Iv4B7Ev20_iJg5ni.png)

Add your projectId on the cypress.json file:

    {
        "projectId": ""
    }

Execute tests on Cypress Dashboard with:

npx cypress run --record --key

![](https://cdn-images-1.medium.com/max/2048/0*eg6gpnFE-E3T2YQB.png)

Try your free [Cypress UI automation](https://www.lambdatest.com/cypress-ui-automation?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) testing online.

***In this [System testing](https://www.lambdatest.com/learning-hub/system-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=learning_hub) tutorial, learn why System testing is important and all the intricacies of the System testing process.***

## Setup Cypress Automation Testing with Cloud-based Selenium Grid

While the [Cypress testing](https://www.lambdatest.com/blog/getting-started-with-cypress/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) framework does let you run tests in parallel, achieving optimal browser coverage is impossible when running tests on a local setup. For optimal browser coverage, you need to upgrade your test infrastructure to a Grid-based system so that you can leverage Cypress framework for performing [Cypress UI testing](https://www.lambdatest.com/cypress-ui-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) on different browsers and operating systems.

The need for a cloud-based [cross browser testing](https://www.lambdatest.com/?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) platform like LambdaTest can help resolve the underlying problems to a great extent. Let’s now write a simple Cypress automation testing and see it in action on the LambdaTest platform.

**Step 1: Create a new spec file.**

Create a new spec file google.spec.js under /cypress/integration folder. In the test code, we are searching Cypress on Google and verifying the results containing Cypress as a keyword.

    describe('Search Cypress on Google',()=&gt;{
      it('Open google site',()=&gt;{ 
          cy.visit('[https://www.google.com/'](https://www.google.com/'))
      })
      
      it('search cypress term in search bar',()=&gt;{ 
          cy.get('[name="q"]').should('be.enabled').type('Cypress{enter}')
      })
      
      it('Check the results of search',()=&gt;{ 
          cy.get('#search').should('be.visible')
          cy.get('#search').contains('Cypress').should('be.visible')
      })
    })

**Step 2: Install the LambdaTest Cypress CLI:**

LambdaTest Cypress CLI enables cross browser testing with Cypress. It lets you test your application across different browsers without any hiccups!

{% youtube T_sJLFLIdow %}

Install lamdatest-cypress cli package using npm install lambdatest-cypress-cli under the project root directory. Once installed, lambdatest-config.json is created using the npx lambdatest-cypress-cli init command, which looks like below:

    {
        "lambdatest_auth": {
           "username": "",
           "access_key": ""
        },
        "browsers": [
           {
              "browser": "Chrome",
              "platform": "Windows 10",
              "versions": [
                 "90.0"
              ]
           },
           {
              "browser": "Firefox",
              "platform": "macOS Big Sur",
              "versions": [
                 "82.0"
              ]
           }
        ],
        "run_settings": {
           "cypress_config_file": "cypress.json",
           "build_name": "LambdaCypress",
           "parallels": 1,
           "specs": "./cypress/integration/*.spec.js",
           "ignore_files": "",
           "npm_dependencies": {
              "cypress": "6.1.0"
           },
           "feature_file_suppport": false
        },
        "tunnel_settings": {
           "tunnel": false,
           "tunnelName": null
        }
    }

In the above config file, we are specifying browsers Chrome and Firefox with the desired versions and platform configurations. As of writing this blog, LambdaTest supports the following browsers and platforms for [Cypress E2E testing](https://www.lambdatest.com/cypress-e2e-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog):

![](https://cdn-images-1.medium.com/max/2048/0*hR0Sk_I_ntPJh2BT.png)

    {
        "name": "cypressdemo",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
          "test": "cypress open",
          "cy:run": "cypress run",
          "record": "cypress run  --record --key ",
          "lambdarun":"lambdatest-cypress run"
        },
        "keywords": [],
        "author": "",
        "license": "ISC",
        "dependencies": {
          "cypress": "^5.6.0",
          "lambdatest-cypress-cli": "^2.0.4",
          "typescript": "^4.1.3"
        }
    }

Run the tests using npm run lambdatest to see the tests in action on the LambdaTest Grid.

![](https://cdn-images-1.medium.com/max/2048/0*Xq3345PV_MW01n1h.png)

You can also view the execution logs in LambdaTest results under the ‘Automation Logs’ option.

![](https://cdn-images-1.medium.com/max/2048/0*5BupF6KegpWRg71E.png)

My recommendations to folks looking for a reliable [automation cloud testing](https://www.lambdatest.com/automate-cloud-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) framework are:

* If your applications are built with modern UI frameworks and need component-based test support, then you might think to switch to Cypress eventually (if not on a priority).

* Switch to Cypress automation testing if current tests show flakiness and have to be revamped for betterment.

* If you are building a new automated framework that works hand in hand with development and deployment, then a POC on Cypress automation testing is worth a try!

## Wrapping Up Cypress Tutorial

Trim down your test cycles by executing [Cypress parallel testing](https://www.lambdatest.com/cypress-parallel-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) online with LambdaTest. In this Cypress tutorial, we covered the basics of the Cypress [test automation](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov09_kj&utm_term=kj&utm_content=blog) framework and how its modern architecture resolves the problems faced in modern web automation testing.

We also looked into its open-source test runner and paid Dashboard services and tried our hands-on with Cypress tests on cloud-based grid LamdaTest. It helps perform cross browser testing with Cypress, along with running tests in parallel on a reliable and scalable cloud grid.

Take this certification to showcase your expertise with end-to-end testing using Cypress automation testingand stay one step ahead.

Here’s a short glimpse of the Cypress 101 certification from LambdaTest:

{% youtube qL_rgUEI2s0 %}
Happy Testing!