Cypress Testing: A Full Guide to Automating Web Applications

Cypress is a modern JavaScript-based E2E (End-to-End) testing framework designed for modern web applications. As a Cypress tool for automation, it enables developers to write fast, reliable, and maintainable tests for web applications. It provides a powerful and easy-to-use way to automate tests. It is primarily used for testing web applications and can be integrated with various tools and frameworks like React, Angular, Vue, and more. Its unique features, like time travel and automatic waiting, can significantly improve the efficiency and reliability of your testing process.In this blog, we will deep dive into how to set up Cypress to perform End to End testing with Cypress locally.

What is Cypress Testing Framework ?

Cypress is a popular open-source testing framework that is primarily used for web application testing. It is built using JavaScript, so if you are wondering what language Cypress uses, the answer is JavaScript, which makes it a great fit for front-end developers.

Many new testers often ask, Is Cypress a framework or just a library? Cypress is indeed a complete end-to-end testing framework built on JavaScript for fast and interactive browser testing.

One of the key advantages of Cypress over other testing frameworks like Selenium is that it doesn’t require the use of driver binaries. Unlike Selenium, which uses the WebDriver protocol, the Cypress WebDriver-free model interacts directly with the browser, resulting in faster and more stable execution.

Cypress automation testing runs on a [Node.js](https:/ odejs.org) server. To create a connection between the browser and the Node.js server, Cypress uses the WebSocket protocol. WebSockets provide full-duplex communication, which allows Cypress to send commands, such as navigating to URLs, interacting with elements, and making assertions, from the test code to the browser in real-time. It also enables Cypress to receive feedback, such as DOM snapshots, console logs, and other test-related information, from the browser back to the server.

How Cypress Test Execution Works:

  • A user operates the web application.
  • Cypress test code issues commands to the Cypress Runner.
  • The Runner talks to a proxy server.
  • The proxy forwards those requests to the application server.
  • The application server handles the requests and returns responses.
  • The Runner records screenshots and video footage throughout the test.
  • Engineers review the results to confirm the application behaves as expected.

Why Cypress For Automation Testing

  • Simple installation: Cypress can be added to a project without extra dependencies, making it easy to adopt for new or existing codebases.
  • Automatic waiting: The framework waits for elements to become available before acting, handling asynchronous behavior and removing the need for manual waits or sleeps.
  • Live reloads: When test files or application code change, Cypress refreshes the runner automatically, giving immediate feedback and speeding up debugging.
  • Time-travel debugging: Cypress captures snapshots at each step, letting you move backward and forward in a test to examine state and diagnose failures.
  • Interactive runner UI: The test runner shows the application in real time, allowing you to interact, inspect elements, and view command logs and assertions.
  • Built-in debugging: You can pause execution at any point and examine the app’s state, and you may also use the browser’s dev tools alongside Cypress.
  • Network and XHR manipulation: Cypress lets you stub, mock, or modify network requests and responses, enabling testing of various scenarios without real HTTP calls.
  • Cross-browser support: Tests can run across multiple browsers, and Cypress offers plugins for integration with CI systems and cloud testing platforms.

Install Cypress

To start with Cypress testing, we need to set up Cypress first. To create a new project for Cypress automated testing, follow the steps below:

  1. Install Node.js: Cypress requires Node.js to run. Download and install [Node.js](https:/

odejs.org) from the official website if you haven’t already. Ensure you have Node.js version 16 or above.

  1. Create a new project: Open your terminal or command prompt and navigate to the directory where you want to set up your Cypress project.
  2. Initialize a new Node.js project:

“ npm init -y “

  1. Install Cypress:

“ npm install cypress --save-dev ` or ` yarn add cypress --dev “

  1. Run the Cypress runner:

“ yarn cypress open ` or ` npx cypress open “ Select E2E Testing from the wizard and you will see the default test cases provided by Cypress.

Folder structure of the Cypress Framework

The screenshots below demonstrate how Cypress creates a default folder hierarchy when it first launches. Below is a detailed description of each of these files and folders that the Cypress framework has.

| Directory/File | Description | |—|—| | cypress/ | Main directory containing all Cypress-related files. | | fixtures/ | Contains JSON files that store static test data (e.g., sample API responses or form inputs). | | e2e/ | Holds your test files (spec files). You can organize tests into folders based on application features or modules. | | support/ | Contains helper files such as commands.js and e2e.js. | | cypress.config.js | Configuration file to alter a project’s default setup settings. | | nodemodules/ | Contains the dependencies installed for your Cypress project. | | package.json | Holds metadata about the project and its dependencies.

Create Test File in Cypress

Create a new test file under cypress/e2e/ to run an E2E test case, e.g., loginAndTabFunctionality.cy.js.

Write Your Test

Cypress supports the Mocha framework. Below is a simple example that demonstrates basic test structure and commands.

/// <reference types="cypress" />
describe("Verify Login/Logout And Tab functionality", () => {
  beforeEach(() => {
    cy.visit("[https://example.com/"](https://example.com/"))
    cy.get('[title="Sign in"]').click()
    cy.get("#email").clear().type("user@example.com");
    cy.get("#password").clear().type("password");
    cy.get(".signin-button").click();
  });
  afterEach(() => {
    cy.get("[data-toggle='dropdown']").click();
    cy.contains("Logout").click();
    cy.contains("Forgot Password?");
  });
  it("Login and Click on 'Codeless' link Under Automation Section", function () {
    cy.contains('Dashboard')
    cy.get("#tgtestcase").click();
    cy.contains("Lets get you started with codeless automation");
  });
  it("Open The Link 'Real Device Cloud' in New Tab and Back To Parent Page", function () {
    cy.get('[id="realdeviceli"] > a').invoke("removeAttr", "target").click();
    cy.url().should("include", "/devicecloud");
    cy.contains('Device Groups')
    cy.go("back");
    cy.contains("the expected text");
  });
});

Automate Your First Cypress Test Case

Test Scenario

  1. Open the application (replace with your own URL).
  2. Sign in using valid credentials.
  3. Confirm the login succeeded by checking for the text “Dashboard”.
  4. Click the “Codeless” link inside the Automation section.
  5. Verify the message “Let’s get you started with codeless automation” appears.
  6. Open the “Real Device Cloud” link in a new tab and then return to the original page.
  7. Check for the expected text to ensure the user is back on the parent page.

Execute The Test Cases Locally

To execute the test cases, you can use Cypress commands in your terminal. You can run Cypress tests in either headed or headless mode, depending on whether you need real-time visibility or faster background execution.

Run Test Cases In Headed Mode:

Open your terminal, navigate to the directory where your Cypress tests are located, and run the command yarn cypress open or npx cypress open. Click on E2E testing, select the browser, and execute the test case from the list.

Run Test case in Headless Mode

By default, Cypress runs in “headless mode”, where the browser runs in the background without opening a visible browser window.

Run the command:

yarn cypress run --spec cypress/e2e/cypresstestgrid_testcase/loginAndTabFunctionality.cy.js

Best Practices for Cypress Test Automation

Every tool has some best practices that can help maximize its effectiveness and efficiency. Below are a few best practices of Cypress.

Avoid Unnecessary Wait

Suppose you have a scenario where you want to test the visibility of an element after clicking on a button. Instead of using a static cy.wait() command, which introduces unnecessary waiting time, you can use Cypress commands like cy.get() with assertions to wait for the element to become visible.

describe('Avoid Unnecessary Waits Example', () => {
  it('should check visibility after button click', () => {
    cy.visit('[https://example.com'](https://example.com'))
    cy.get('#myButton').click()
    cy.get('#myElement')
      .should('be.visible')
      .and('have.text', 'Expected Text')
  })
})

Set baseUrl in the Cypress configuration file

Hard-coding the baseUrl using cy.visit() in the before() block of each spec file is not the best approach. With the baseUrl set in the configuration file, Cypress will automatically prepend this base URL to any relative URLs used in your tests.

const { defineConfig } = require("cypress");
module.exports = defineConfig({
  e2e: {
    baseUrl: "[https://example.com"](https://example.com"),
    experimentalStudio: true,
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
  },
});

Multiple assertions per test in Cypress

Writing a single assertion in a test can make it run more slowly and lead to problems with performance. The recommended practice is to add multiple assertions with a single command, which speeds up testing and improves test clarity and organization.

cy.get('.element')
  .should('have.class', 'active')
  .and('be.visible')
  .and('have.text', 'Hello World');

Isolate it() blocks

Each it() block should be independent and self-contained, with its own setup and teardown steps. This ensures that tests can run independently of each other, making them more robust and reliable.

describe('Test Suite', () => {
  beforeEach(() => {
    cy.visit('/');
  });
  afterEach(() => {
    // Cleanup tasks, if any
  });
  it('Test Case 1', () => {
    cy.get('.element').should('have.class', 'active');
    cy.get('.element').should('be.visible');
  });
  it('Test Case 2', () => {
    cy.get('.other-element').should('have.text', 'Hello World');
    cy.get('.other-element').click();
  });
});

Keeping test data separate

Cypress allows you to define test data in external JSON files called fixtures. This keeps your test code clean and separates concerns between test logic and test data.