JavaScript and Cypress framework for Modern UI Automation

JavaScript and Cypress framework for Modern UI Automation

Ensuring smooth functionality and an excellent user experience for web applications is more important than ever in today’s digital world. As web applications become increasingly complex, however, traditional testing methods often struggle to meet the demands of modern development. Modern UI automation frameworks, therefore, offer powerful tools for comprehensive and reliable testing. 

JavaScript, the backbone of web development, is central to many automation frameworks due to its versatility. Cypress, in fact, has gained popularity for its ease of use, powerful features, and developer-friendly approach, making it a standout in this space. It also streamlines the process of writing, executing, and maintaining automated tests, making it an essential tool for developers and testers alike. 

In this blog, we’ll delve into Modern UI automation with JavaScript and Cypress, starting with the setup and then moving on to advanced features like real-time reloading and CI pipeline integration. By the end, you’ll have the knowledge to effectively automate UI testing for modern web applications, whether you’re a seasoned developer or new to automation

Prerequisites for Modern UI Automation Framework

Before embarking on your journey with JavaScript and Cypress for Modern UI Automation, ensure you must have the following tools in your system and some basic understanding of the technologies i.e. Cypress, Automation, JavaScript and some coding knowledge.

Node.js and npm 

Both Node.js and npm are essential for managing dependencies and running your Cypress tests. 

VS Code

VS Code offers a powerful and user-friendly environment for working with JavaScript but also seamlessly integrates with the Cypress framework for modern UI automation. It provides syntax highlighting, code completion, debugging tools, and extensions that can significantly enhance your development experience.

Basic Understanding of JavaScript 

Familiarity with fundamental JavaScript concepts like variables, functions, and object-oriented programming will therefore crucial for writing automation scripts and interacting with the browser. 

Cypress 

Cypress is the core framework for your end-to-end (E2E) tests; consequently, it offers a user-friendly interface and powerful capabilities for interacting with web elements. 

Here, we’ve looked at the things we need before we start. 

Installation for Modern UI Automation Framework

How to Install Node.js on Windows? 

What is Node.js? 

Node.js is a runtime environment that enables JavaScript to run outside of a web browser; consequently, it allows developers to build scalable and high-performance server-side applications. Originally, JavaScript was confined to client-side scripting in browsers, but with Node.js, it can now power the backend as well. 

For testers, Node.js unlocks powerful automation capabilities but also supports tools and frameworks like WebDriver.io and Puppeteer, which automate browser interactions, manage test suites, and perform assertions. Node.js also facilitates custom test frameworks and seamless integration with testing tools. Additionally, it enables running tests in headless environments, ideal for continuous integration pipelines. Overall, Node.js enhances the effectiveness of JavaScript-based testing, improving software quality, speeding up development and UI Automation. 

Key Features of Node.js

  • Asynchronous and Event-Driven: Node.js library APIs work asynchronously; consequently, they are non-blocking. The server moves to the next API call without waiting for the previous one to complete, therefore it using event mechanisms to handle responses efficiently. 
  • High Speed: Built on Google Chrome’s V8 JavaScript engine, Node.js therefore executes code very quickly. 
  • Single-Threaded but Highly Scalable: Node.js uses a single-threaded model with event looping. This event-driven architecture allows the server to respond without blocking, making it highly scalable compared to traditional servers. Unlike servers like Apache HTTP Server, which create limited threads to handle requests, Node.js can handle thousands of requests using a single-threaded program. 
  • No Buffering: Node.js applications do not buffer data; instead they output data in chunks. 

Steps to Install Node.js on Windows for UI Automation: 

  1. Downloading the Node.js Installer 
    • Visit the official Node.js website: Node.js Downloads 
    • Download the .msi installer for Windows. 
  2. Running the Node.js Installer 
    • Double-click on the .msi installer to open the Node.js Setup Wizard. 
    • Click “Next” on the Welcome to Node.js Setup Wizard screen. 
    • Accept the End-User License Agreement (EULA) by checking “I accept the terms in the License Agreement” and click “Next.” 
    • Choose the destination folder where you want to install Node.js and click “Next.” 
    • Click “Next” on the Custom Setup screen. 
    • When prompted to “Install tools for native modules,” click “Install.” 
    • Wait for the installation to complete and click “Finish” when done. 
  3. Verify the Installation 
    • Open the Command Prompt or Windows PowerShell. 
    • Run the following command to check if Node.js was installed correctly:
    • node -v 
    • If Node.js was installed successfully, the command prompt will print the version of Node.js installed. 

By following these steps, you can install Node.js on your Windows system and start leveraging its capabilities for server-side scripting and automated testing. 

How to Install Visual Studio Code (VS Code) on Windows? 

What is Visual Studio Code (VS Code)? 

Visual Studio Code (VS Code) is a free, open-source code editor developed by Microsoft. It features a user-friendly interface and powerful editing capabilities. VS Code supports a wide range of programming languages and comes with built-in features for debugging, syntax highlighting, code completion, and Git integration. It also offers a vast ecosystem of extensions to customize and extend its functionality. 

Steps to Install VS Code for UI Automation

  1. Visit the Official VS Code Website 
    • Open any web browser like Google Chrome or Microsoft Edge. 
    • Go to the official Visual Studio Code website: VS Code Downloads 
  2. Download VS Code for Windows 
    • Click the “Download for Windows” button on the website to start the download. 
  3. Open the Downloaded Installer 
    • Once the download is complete, locate the Visual Studio Code installer in your downloads folder. 
    • Double-click the installer icon to begin the installation process. 
  4. Accept the License Agreement 
    • When the installer opens, you will be asked to accept the terms and conditions of Visual Studio Code. 
    • Check “I accept the agreement” and then click the “Next” button. 
  5. Choose Installation Location 
    • Select the destination folder where you want to install Visual Studio Code. 
    • Click the “Next” button. 
  6. Select Additional Tasks 
    • You may be prompted to select additional tasks, such as creating a desktop icon or adding VS Code to your PATH. 
    • Select the options you prefer and click “Next.” 
  7. Install Visual Studio Code 
    • Click the “Install” button to start the installation process. 
    • The installation will take about a minute to complete. 
  8. Launch Visual Studio Code 
    • After the installation is complete, a window will appear with a “Launch Visual Studio Code” checkbox. 
    • Check this box and then click “Finish.” 
  9. Open Visual Studio Code 
    • Visual Studio Code will open automatically. 
    • You can now create a new file and start coding in your preferred programming language. 

By following these steps, you have successfully installed Visual Studio Code on your Windows system. You are now ready to start your programming journey with VS Code. 

Create Project for Modern UI Automation Framework

Creating a Cypress project in VS Code is straightforward. Follow these steps to get started:

Steps to Create a Cypress Project in VS Code 

  1. Open VS Code: 
    • Launch VS Code on your computer. 
  2. Click on Files Tab: 
    • Navigate to the top-left corner of the VS Code interface and click on the “Files” tab. 
  3. Select Open Folder Option: 
    • From the dropdown menu, choose the “Open Folder” option. This action will prompt a pop-up file explorer window. 
  4. Choose Project Location: 
    • Browse through the file explorer to select the location where you want to create your new Cypress project. For this example, create a new folder on the desktop and name it “CypressJavaScriptFramework”. 
  5. Open Selected Folder: 
    • Once you’ve created the new folder, select it and click on the “Open” button. VS Code will now automatically navigate to the selected folder. 

Congratulations! You’ve successfully created a new Cypress project in VS Code. On the left panel of VS Code, you’ll see your project name, and a welcome tab will appear in the editor. 

Now, we are all set to start building your Cypress project in Visual Studio Code! 

What is Cypress?

Cypress is a modern, open-source test automation framework designed specifically for web applications and used to UI automation also. Unlike many other testing tools that run outside of the browser and execute remote commands, Cypress operates directly within the browser. This unique architecture enables Cypress to offer fast, reliable, and easy-to-write tests, making it an invaluable tool for developers and testers. 

Cypress’s architecture allows it to control the browser in real-time, providing access to every part of the application being tested. This direct control means that tests can interact with the DOM, make assertions, and simulate user interactions with unparalleled accuracy and speed.

Cypress Architecture for Modern UI Automation Framework:

Cypress Architecture for Modern UI Automation Framework

Cypress automation testing operates on a NodeJS server. It uses the WebSocket protocol to create a connection between the browser and the Node.js server. WebSocket’s allow full-duplex communication, enabling Cypress to send commands and receive feedback in real time. This means Cypress can navigate URLs, interact with elements, and make assertions, while also receiving DOM snapshots, console logs, and other test-related information from the browser. 

Let’s break down the components and how they interact: 

  1. User Interaction
    • The process begins with a user interacting with the web application. This includes actions like clicking buttons, selecting values from drop-down menus, filling forms, or navigating through pages. 
  2. Cypress Test Scripts
    • Developers write test scripts using JavaScript or TypeScript. These scripts simulate user interactions and verify that the application behaves as expected. 
  3. Cypress Runner
    • The Cypress Runner executes the test scripts. It interacts with the web application, capturing screenshots and videos during the tests. 
  4. Proxy Server
    • A proxy server sits between the Cypress Runner and the web application. It intercepts requests and responses, allowing developers to manipulate them. 
  5. Node.js
    • Cypress runs on Node.js, providing a runtime environment for executing JavaScript or TypeScript code. 
  6. WebSocket
    • The WebSocket protocol enables real-time communication between the Cypress Runner and the web application. 
  7. HTTP Requests/Responses
    • HTTP requests (e.g., GET, POST) and responses are exchanged between the Cypress Runner and the application server, facilitating the testing process. 

By understanding these components and their interactions, you can better appreciate how Cypress effectively automates testing for modern web applications and UI Automation. 

Features of the Cypress

  • Time Travel: Cypress captures snapshots of your application as it runs, allowing you to hover over each command in the test runner to see what happened at every step. 
  • Real-Time Reloads: Cypress automatically reloads tests in real-time as you make changes, providing instant feedback on your changes without restarting your test suite. 
  • Debuggability: Cypress provides detailed error messages and stack traces, making it easier to debug failed tests. It also allows you to use browser developer tools for debugging purposes. 
  • Automatic Waiting: Cypress automatically waits for commands and assertions before moving on, eliminating the need for explicit waits or sleeps in your test code. 
  • Spies, Stubs, and Clocks: Cypress provides built-in support for spies, stubs, and clocks to verify and control the behavior of functions, timers, and other application features. 
  • Network Traffic Control: Cypress allows you to control and stub network traffic, making it easier to test how your application behaves under various network conditions. 
  • Consistent Results: Cypress runs in the same run-loop as your application, ensuring that tests produce consistent results without flaky behavior. 
  • Cross-Browser Testing: Cypress supports testing across multiple browsers, including Chrome, Firefox, and Edge, ensuring your application works consistently across different environments. 
  • CI/CD Integration: Cypress integrates seamlessly with continuous integration and continuous deployment (CI/CD) pipelines, enabling automated testing as part of your development workflow.

Advantages of Cypress

  • Easy Setup and Configuration: Cypress offers a simple setup process with minimal configuration, allowing you to start writing tests quickly without dealing with complex setup procedures. 
  • Developer-Friendly: Cypress is designed with developers in mind, providing an intuitive API and detailed documentation that makes it easy to write and maintain tests. 
  • Fast Test Execution: Cypress runs directly in the browser, resulting in faster test execution compared to traditional testing frameworks that operate outside the browser. 
  • Reliable and Flake-Free: Cypress eliminates common sources of flakiness in tests by running in the same run-loop as your application, ensuring consistent and reliable test results. 
  • Comprehensive Testing: Cypress supports a wide range of testing types, including end-to-end (E2E), integration, and unit tests, providing a comprehensive solution for testing web applications. 
  • Rich Ecosystem: Cypress has a rich ecosystem of plugins and extensions that enhance its functionality and allow you to customize your testing setup to suit your specific needs. 
  • Active Community and Support: Cypress has an active and growing community that provides support, shares best practices, and contributes to the development of the framework. 
  • Seamless CI/CD Integration: Cypress integrates seamlessly with CI/CD pipelines, enabling automated testing as part of your development workflow. This integration ensures that tests are run consistently and reliably in different environments, improving the overall quality of your software. 

Cypress’s unique features, reliability, and ease of use make it an ideal choice for developers and testers looking to ensure the quality and performance of their web applications.  

By leveraging Cypress in your JavaScript projects, you can achieve efficient and effective UI automation, enhancing the overall development lifecycle. 

Cypress Framework Structure 

In a Cypress project, the folder structure is well-defined to help you organize your test code, configuration, plugins, and related files. Here’s a breakdown of the typical folders and files we will encounter:

1. cypress/ Directory 

  • Purpose: This is the root directory where all Cypress-related files and folders reside. 

2. cypress/e2e/ Directory 

  • Purpose: This is where you should place your test files. 
  • Details: Cypress automatically detects and runs tests from this folder. Test files typically have .spec.js or .test.js file extensions. 

3. cypress/fixtures/ Directory (Optional) 

  • Purpose: Store static data or fixture files that your tests might need. 
  • Details: These can include JSON, CSV, or text files. 

4. cypress/plugins/ Directory (Optional) 

  • Purpose: Extend Cypress’s functionality. 
  • Details: Write custom plugins or modify Cypress behavior through plugins. 

5. cypress/support/ Directory (Optional) 

  • Purpose: Store various support files, including custom commands and global variables. 
  • Details
    • commands.js (Optional): Define custom Cypress commands here to encapsulate frequently used sequences of actions, making your test code more concise and maintainable. 
    • e2e.js (Optional): Include global setup and teardown code for your Cypress tests. This file runs before and after all test files, allowing you to perform tasks like setting up test data or cleaning up resources. 

6. cypress.config.js File 

  • Purpose: Customize settings for Cypress, such as the base URL, browser options, and other configurations. 
  • Location: Usually found in the root directory of your Cypress project. 
  • Details: You can create this file manually if it doesn’t exist or generate it using the Cypress Test Runner’s settings. 

7. node_modules/ Directory 

  • Purpose: Contains all the Node.js packages and dependencies used by Cypress and your project. 
  • Details: Usually, you don’t need to change anything in this folder. 

8. package.json File 

  • Purpose: Defines your project’s metadata and dependencies. 
  • Details: Used to manage Node.js packages and scripts for running Cypress tests. 

9. package-lock.json File 

  • Purpose: Ensures your project dependencies remain consistent across different environments. 
  • Details: Automatically generated and used by Node.js’s package manager, npm. 

10. README.md File (Optional) 

  • Purpose: Include documentation, instructions, or information about your Cypress project. 

11. Other Files and Folders (Project-Specific) 

  • Purpose: Depending on your project’s needs, you may have additional files or folders for application code, test data, reports, or CI/CD configurations. 

Folder Structure Overview 

The folder structure is designed to keep your Cypress project organized and easy to maintain:

  • Main Directories
    • cypress/e2e/: Where you write your tests. 
    • cypress.config.js: Where you configure Cypress. 
  • Optional Directories
    • fixtures/: For test data. 
    • plugins/: For extending Cypress functionality. 
    • support/: For custom commands and utilities. 

This structure helps you customize your testing environment and keep everything well-organized. 

Now let’s start to install Cypress and Configure in our project.

Cypress Install and Configuration:

We’re now ready to dive into the Cypress installation and configuration process. With Node.js, VS Code, and a new project named “CypressJavaScriptFramework” set up, let’s walk through configuring Cypress step-by-step. 

  1. Open Your Project: Start by opening the “CypressJavaScriptFramework” project in VS Code. 
  2. Open a New Terminal: From the top-left corner of VS Code, open a new terminal. 
  3. Initialize Node.js Project: Verify your directory path and run the below command to initialize a new Node.js project and generate a package.json file. 
    • npm init –y 
  4. Install Cypress: Install Cypress as a development dependency with the below command. Once installed, you’ll find Cypress listed in your package.json file. As of this writing, the latest version is 13.13.1. 
    • npm install –save-dev cypress  
  5. Configure Cypress: To open the Cypress Test Runner, run the below command. 
    • npx cypress open

Upon first launch, you’ll be greeted by Launchpad, which helps with initial setup and configuration. 

Step 1: Choosing a Testing Type

The first decision we will make in the Launchpad is selecting the type of testing you want to perform: 

  • E2E (End-to-End) Testing: This option runs your entire application and visits pages to test them comprehensively. 
  • Component Testing: This option allows you to mount and test individual components of your app in isolation. 

Here we must select E2E Testing. 

What is E2E Testing? 

End-to-End (E2E) testing is a method of testing that validates the functionality and performance of an application by simulating real user scenarios from start to end. This approach ensures that all components of the application, including the frontend and backend, work together seamlessly. 

After selecting E2E Testing Configuration Screen where we just have to click on Continue button.

Step 2: Quick Configuration 

Next, the Launchpad will automatically generate a set of configuration files tailored to your chosen testing type. You’ll see a list of these changes, which you can review before continuing. For detailed information about the generated configuration, you can check out the Cypress configuration reference page. 

After clicking on Continue button we will notice some changes in the framework few Configuration files will be added in the Framework which are 
cypress.config.js 
cypress/ directory 
cypress directory Fixtures and Support directory 

The description of these file s and folders we have seen in start of blog.

Step 3: Launching a Browser 

Finally, the Launchpad will display a list of compatible browsers detected on your system. You can select any browser to start your testing. Don’t worry if you want to switch browsers later; Cypress allows you to change browsers at any point of time.  

As in my system I have Chrome and Edge browser installed. Cypress also have the inbuild browser which is called as “Electron” 

What is Electron Browser? 

Electron is an open-source framework that allows developers to build cross-platform desktop applications using web technologies like HTML, CSS, and JavaScript. It combines the Chromium rendering engine and the Node.js runtime, enabling you to create desktop apps that function seamlessly across Windows, macOS, and Linux.

Key Points: 

  • Cross-Platform Compatibility: Develop applications that work on Windows, macOS, and Linux. 
  • Chromium-Based: Uses Chromium, the same rendering engine behind Google Chrome, for a consistent browsing experience. 
  • Node.js Integration: Allows access to native OS functionalities via Node.js, blending web technologies with desktop capabilities. 
  • Used by Popular Apps: Many well-known applications like Slack, Visual Studio Code, and GitHub Desktop are built using Electron. 

Electron provides the flexibility to build powerful desktop applications with the familiarity and ease of web development. 

Now, you’re ready to hit the start button and embark on your testing journey with Cypress! 

In this article we will use chrome browser for that we have to select Chrome and click on “Start E2E Testing in Chrome”. Then we will land on Cypress runner screen here we have 2 options   

  • Scaffold example specs: Automatically generate example test specifications to help you get started with Cypress. 
  • Create new specs: Manually create new test specifications to tailor your testing needs and scenarios. 

Here we will use Scaffold example specs.  

Scaffolding Example Specs 

Use: Scaffolding example specs in Cypress generates predefined test files that demonstrate how to write and structure tests. 

Reason: Providing example specs helps new users quickly understand Cypress’s syntax and best practices, making it easier to start writing their own tests and ensuring they follow a proper testing framework. 

Once we select Scaffold example specs option, we will notice in framework few files are added in cypress directory under e2e directory. 

Finally, we have installed cypress, configured and now we can run Scaffolding Example Specs. Now we will add our own file and execute it with cypress runner and from Command Line. Before that we will go through the Cypress Testing components. 

Cypress Testing Components 

Let’s understand Cypress Testing Components used while automation. 

  • describe() Block: Groups related tests and provides structure. 
  • it() Blocks: Defines individual test cases, focusing on specific functionalities. 
  • Hooks: Manage setup and teardown processes to maintain a consistent test environment. 
  • Assertions: Verify that the application behaves as expected by comparing actual results to expected results. 

describe() Block 

The describe() block in Cypress is used to group related test cases together. It defines a test suite, making it easier to organize and manage your tests. 

Purpose: 

The describe() block provides a structure for your test cases, allowing you to group tests that are related to a particular feature or functionality. It helps in maintaining a clean and organized test suite, especially as your test cases grow in number. 

Example: 

it() Blocks 

The it() block defines individual test cases within a describe() block. It contains the actual code for testing a specific aspect of the feature under test. 

Purpose: 

Each it() block should test a single functionality or scenario, making your test cases clear and focused. This helps in identifying issues quickly and understanding what each test is verifying. 

Example:

Hooks 

Hooks are special functions in Cypress that run before or after tests. They are used to set up or clean up the state and perform common tasks needed for your tests. 

Types of Hooks: 

  • before(): Executes once before all tests in a describe() block. 
  • beforeEach(): Runs before each it() block within a describe() block. 
  • after(): Executes once after all tests in a describe() block. 
  • afterEach(): Runs after each it() block within a describe() block. 

Purpose: 

Hooks are useful for setting up test environments, preparing data, and cleaning up after tests, ensuring a consistent and reliable test environment. 

Example: 

Assertions 

Assertions are statements that check if a condition is true during the test execution. They verify that the application behaves as expected and helps identify issues when the actual results differ from the expected results. 

Purpose: 

Assertions validate the outcomes of your test cases by comparing actual results against expected results. They help ensure that your application functions correctly and meets the defined requirements. 

Example: 

These components work together to create a comprehensive and organized test suite in Cypress, ensuring your application is thoroughly tested and reliable. 

Create Test File 

Before diving into test file creation, let’s define the functionalities. We will automate the Calculator.net web application and will focus on basic arithmetic operations: addition, subtraction, multiplication, and division. 

Here’s a breakdown of the test scenarios:

1. Verify user able to do addition 

  • Visit Calculator.net 
  • Click on two numbers (e.g., 1 and 2) 
  • Click the “+” operator 
  • Click on another number (e.g., 1) 
  • Click the “=” operator 
  • Verify the result is equal to 3 
  • Click the “reset” button 

2. Verify user able to do Subtraction 

  • Visit Calculator.net 
  • Click on a number (e.g., 3) 
  • Click the “-” operator 
  • Click on another number (e.g., 1) 
  • Click the “=” operator 
  • Verify the result is equal to 2 
  • Click the “reset” button 

3. Verify user able to do Multiplication 

  • Visit Calculator.net 
  • Click on a number (e.g., 2) 
  • Click the “*” operator 
  • Click on another number (e.g., 5) 
  • Click the “=” operator 
  • Verify the result is equal to 10 
  • Click the “reset” button 

4. Verify user able to do Division 

  • Visit Calculator.net 
  • Click on a number (e.g., 8) 
  • Click the “/” operator 
  • Click on another number (e.g., 2) 
  • Click the “=” operator 
  • Verify the result is equal to 4 
  • Click the “reset” button

Optimizing with Hooks: 

As you noticed, visiting Calculator.net and resetting the calculator are common steps across all scenarios. To avoid code repetition, we’ll utilize Cypress hooks: 

  • beforeEach: Execute this code before each test case. We’ll use it to visit Calculator.net. 
  • afterEach: Execute this code after each test case. We’ll use it to reset the calculator. 

Now, let’s create the test file and add the code below to Calculator.cy.js file.  

Let’s create a Selectors.json file to store all the selectors used in automation, assigning them meaningful names for better organization. 

The Selector.json file is a crucial part of your test automation framework. It centralizes all the CSS selectors used in your tests, making the code more maintainable and readable. By keeping selectors in a dedicated file, you can easily update or change any element locator without modifying multiple test scripts. 

Purpose: 

  • Centralization: All element selectors are stored in one place. 
  • Maintainability: Easy to update selectors if the application’s HTML changes. 
  • Readability: Makes test scripts cleaner and easier to understand by abstracting the actual CSS selectors. 

Add the following JSON content to your Selector.json file in the cypress/fixtures directory: 

  • Number Buttons: Selectors for the number buttons (0-9) use the span[onclick=’r(number)’] pattern, identifying the buttons by their onclick attribute values specific to each number. 
  • Operator Buttons: Selectors for the arithmetic operators (plus, minus, multiply, divide) use a similar pattern but include escaped quotes for the operator characters. 
  • Equals Button: The selector for the equals button follows the same pattern, identifying it by its onclick attribute. 
  • Result: The selector for the result display uses an ID (#sciOutPut), directly identifying the output element. 
  • Cancel Button: The selector for the cancel button is included to reset the calculator between tests, ensuring a clean state for each test case. 

By utilizing this Selector.json file, your test scripts can reference these selectors with meaningful names, thereby enhancing the clarity and maintainability of your test automation framework for UI.

Advanced Configuration In cypress.config.js: 

While installing and Configration of cypress we have created cypress.config.js file. Now we will look at the Advanced configuration in cypress.config.js allows you to tailor Cypress’s behavior to fit the specific needs of your project, optimizing and enhancing the testing process. 

Key Benefits: 

  • Customization: You can set up custom configurations to suit your testing environment, such as base URL, default timeouts, viewport size, and more. 
  • Environment Variables: Manage different environment settings, making it easy to switch between development, staging, and production environments. 
  • Plugin Integration: Configure plugins for extended functionality, such as code coverage, visual testing, or integrating with other tools and services. 
  • Reporter Configuration: Customize the output format of your test results, making it easier to integrate with CI/CD pipelines and other reporting tools. 
  • Browser Configuration: Define which browsers to use for testing, including headless mode, to speed up the execution of tests. 
  • Test Execution Control: Set up retries for flaky tests, control the order of test execution, and manage parallel test runs for better resource utilization. 
  • Security: Configure authentication tokens, manage sensitive data securely, and control network requests and responses to mimic real-world scenarios. 

Add below code to cypress.config.js file.

This Cypress configuration file (cypress.config.js) sets various options to customize the behavior of Cypress tests. Here’s a breakdown of the configuration for modern UI Automation: 

  • const { defineConfig } = require(“cypress”);: Import defineConfig function from Cypress, which is used to define configuration settings. 
  • module.exports = defineConfig({ … });: Exports the configuration object, which Cypress uses to configure the test environment. 
    • projectId: “CYFW01”: Specifies a unique project ID for identifying the test project. This is useful for organizing and managing tests in CI/CD pipeline. 
    • downloadsFolder: “cypress/downloads”: Sets the folder where files downloaded during tests will be saved. 
    • screenshotsFolder: “cypress/screenshots”: Defines the folder where screenshots taken during tests will be stored, particularly for failed tests. 
    • video: true: Enables video recording of test runs, which can be useful for reviewing test execution and debugging. 
    • screenshotOnRunFailure: true: Configures Cypress to take screenshots automatically when test fails. 
    • chromeWebSecurity: false: Disables web security in Chrome, which can be useful for testing applications that involve cross-origin requests. 
    • trashAssetsBeforeRuns: true: Ensures that previous test artifacts (like screenshots and videos) are deleted before running new tests, keeping the test environment clean. 
    • viewportWidth: 1920 and viewportHeight: 1080: To simulate a screen resolution of 1920×1080 pixels, you can set the default viewport size for tests accordingly.
    • execTimeout: 10000: Configures the maximum time (in milliseconds) Cypress will wait for commands to execute before timing out. 
    • pageLoadTimeout: 18000: Sets the maximum time (in milliseconds) Cypress will wait for a page to load before timing out. 
    • defaultCommandTimeout: 10000: Defines the default time (in milliseconds) Cypress will wait for commands to complete before timing out. 
    • retries: { runMode: 1, openMode: 0 }
      • runMode: 1: Specifies that Cypress should retry failed tests once when running in CI/CD mode (runMode). 
      • openMode: 0: Indicates that Cypress should not retry failed tests when running interactively (openMode). 
    • e2e: { setupNodeEvents(on, config) { … } }: Provide way to set-up Node.js event listeners for end-to-end tests. This is where you can implement custom logic or plugins to extend Cypress’s functionality. 

Executing Test Cases Locally for Modern UI Automation

To run test cases for modern UI Automation, use Cypress commands in your terminal. Cypress supports both headed mode (with a visible browser window) and headless mode (where tests run in the background without displaying a browser window). 

Running Test Cases in Headed Mode: 

  • Open your terminal. 
  • Navigate to the directory containing your Cypress tests. 
  • Execute the tests in headed mode using the below command: 
    • npx cypress open 

This will open the Cypress Test Runner. Click on “E2E Testing,” select the browser, and run the test case from the list (e.g., calculator.cy.js). Once selected, the test case will execute, and you can see the results in real-time. Screenshots of the local test execution are provided below. 

Running Test Cases in Headless Mode: 

Headless mode in Cypress refers to running test cases without a visible user interface. This method allows tests to be executed entirely in the background. Here’s how you can set up and run Cypress in headless mode. 

To run the test script directly from the command line, use the following command: 

npx cypress run –spec “cypress\e2e\Calculator.cy.js” –browser edge 

By default, Cypress executes tests in headless mode, but you can also specify it explicitly using the –headless flag: 

npx cypress run — headless –spec “cypress\e2e\Calculator.cy.js” –browser edge 

This enables efficient and automated test execution without launching the browser UI (UI Automation). 

headless UI automation1
headless UI automation 2

Conclusion 

In this blog, we explored how the JavaScript and Cypress framework revolutionize modern UI automation. By leveraging Cypress’s powerful features, such as its intuitive API, robust configuration options, and seamless integration with JavaScript, we were able to effectively test complex web applications.

We delved into practical implementations of modern UI automation such as: 

  • Creating and managing test cases with Cypress, including various operations like addition, subtraction, multiplication, and division using a calculator example. 
  • Using advanced configuration in cypress.config.js to tailor the test environment to specific needs, from handling different environments and customizing timeouts to integrating plugins and managing network requests. 
  • Implementing selectors through a Selector.json file to enhance test maintainability and clarity by using descriptive names for elements. 
  • Executing tests locally in both headed and headless modes, providing insights into how to monitor test execution in real-time or run tests in the background. 

By incorporating these strategies, we ensure that our web applications not only function correctly but also provide a seamless and reliable user experience. Cypress’s modern approach to UI testing simplifies the automation process, making it easier to handle the dynamic nature of contemporary web applications while maintaining high standards of quality and performance. 

https://github.com/spurqlabs/JavaScript-Cypress-WebAutomation

Click here to read more blog like this.

XPath for Selenium, Playwright & Cypress Web Automation Testing

XPath for Selenium, Playwright & Cypress Web Automation Testing

For any web automation testing, the one and most important task is to identify and use robust locators to identify web elements so that your automated tests do not fail with “Unable to locate element”. In this article, we are providing you with the techniques that every tester should learn to create those robust locators. As we already know this can be done using different locator strategies. In this blog, we are going to learn about XPath. Before we dive into the topic of our discussion let’s just get more familiar with Xpaths. Let’s start with, 

What is XPath?

XPath (XML Path Language) is an expression language that allows the processing of values conforming to the data model defined in the XQuery and XPath Data models. Basically, it is a query language that we use to locate or find an element present on the webpage. It is defined by the World Wide Consortium (W3C). Now, let’s discuss why Xpaths are necessary.

Why is XPaths necessary?

Xpaths are the most widely used locators in automation though there are other locators like id, name, class name, tag name, and so on. Also, it is used when there are no unique attributes available to locate the web element. It allows identification with the help of the visible test present on the screen with the help of Xpath function text().

Before explaining the importance of XPath let’s just go through the different types of locators available for automation testing. 

In this blog, we will learn about the different types of Xpaths and how to implement them so that we can locate our web elements quickly using the selenium web driver. Basically, there are two types of Xpaths

1. Absolute XPath:

In this type, The XPath starts from the beginning or from the root node of the HTML DOM structure. It is a direct way to locate or find the web element but the disadvantage of absolute XPath is that as we are creating it from the start of the HTML DOM structure if there are any changes introduced in the created path of the web element then it gets failed. In this type of locator, we only use tags or nodes. The main advantage of this is that we can select a web element from the root node as it starts with the single forward slash “ / ”.

Example:

Here is an example of an absolute Xpath for an input field box. 

 example of an absolute Xpath for an input field box. 

The absolute XPath is: /html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/form[1]/div[1]/div[1]/div[2]/input[1]

2. Relative Xpath:

Compared to an absolute XPath the relative XPath does not start from the beginning of the HTML DOM structure. It starts from where the element is present e.g. from the middle of the HTML DOM structure if the element is located there. We don’t have to travel from the start of the HTML DOM structure. The relative Xpath starts with a double forward slash “ // “ and it can locate and search the web element anywhere on the webpage. Relative XPath directly jumps to elements on DOM. The other difference between absolute and relative XPath is that in absolute XPath we use tags or nodes but in relative XPath we use attributes. 

Example:

We are writing the relative XPath for the same input field for which earlier we created an absolute XPath. 

We are writing the relative XPath for the same input field for which earlier we created an absolute XPath.

Relative XPath is: 

//input[@name=’username’]

XPath Functions: 

Types of Xpath Functions

It is not always possible to locate a web element using relative XPath that is because at some times while locating a particular web element there is the possibility of elements that have similar properties, for example, the same id, name, or same class name. So, here the basic XPath won’t work efficiently for finding that web element. Xpath functions are used to write the efficient XPath by locating a web element with a unique value. Basically, there are three types of XPath functions as follows,

a. starts-with() Function:

starts-with() function is very useful in locating dynamic web elements. It is used to find the element in which the attribute value starts with some particular character or text. 

While working on the dynamic web page the starts-with function plays an important role. We can use it to match the starting value of a web element that remains static. 

It can also locate the web element whose attribute value is static.

Syntax:

Xpath = //tagname[starts-wtih(@attribute,’value’)]

Example:

//input[starts-with(@name,’username’)]

start-with() function is very useful in locating dynamic web elements. 

b. contains() Function:
  • Just like the start-with() function explained above, the contains() function is also used to create a unique expression to locate a web element. 
  • It is used when if a part of the value of an attribute changes dynamically the function can navigate to the web element with the partial text present. 
  • We can provide any partial attribute value to locate the web element.
  • It accepts two parameters the first one is the attribute of the tag must validate to locate the web element and the second one is the value of an attribute is a partial value that the attribute must contain. 
Syntax: 

Xpath = //tagname[contains(@attribute,’value’)]

Example:

//input[contains(@name,’username’)]

 Xpath contains() Function:
c. text() Function:

text() Function:

  • The text() function is used to locate web elements with exact text matches.
  • The function only works if the element contains the text. 
  • This method returns the text of the web element when identified by the tag name and compared it with the value provided on the right side. 
Syntax:

Xpath = //tagname[text()=’Actual text present’]

Example:

   //button[text()=’ Login ‘]

 Xpath text() Function:

How to use AND & OR in XPath:

AND & OR expressions can also be used in selenium Xpath expressions. Very useful if you want to use more than two attributes to find elements on a webpage. 

The OR expression requires two conditions and it will check whether the first condition in the statement is true if so then it will locate that web element and if not then it will go for the second condition and if that is true then also it will locate that web element. So, here the point we should remember is that when we are using the OR expression at least either of two of the conditions should be true then, and then only it will find and locate that web element. 

Syntax:

Xpath = //tagname[@attribute=’Value’ or @attribute=’Value’]

Example:

//input[@name=’username’ or @placeholder=’xyz’]     

Here the first condition is true and the second one is false still the web element got located. 

How to use AND & OR in Xpath

Just like the OR expression the AND expression also requires two conditions but the catch here is that both the provided condition must be true then and then only the web element will get located. If either of the conditions is false then it will not locate that web element. 

Syntax:

Xpath = //tagname[@attribute=’Value’ and @attribute=’Value’]

Example:

//input[@name=’username’ and @placeholder=’Username’]

In this case, both the condition provided for an AND expression is true hence the web element got located.

XPath Axis:

XPath Axis

It is a method to identify those dynamic elements that are impossible to find by normal XPath methods. All the elements are in a hierarchical structure and can be either located using absolute or relative Xpaths but it provides specific attributes called XPath axis to locate those elements with unique XPath expressions. The axes show a relationship to the current node and help locate the relative nodes concerning the tree’s current node. The dynamic elements are those elements on the webpage whose attributes dynamically change on refresh or any other operations. The HTML DOM structure contains one or more element nodes and they are known as trees of nodes. If an element contains the content, whether it is other elements or text, it must be declared with a start tag and an end tag. The text defined between the start tag and the end tag is the element content. 

Types of XPath Axis: 

XPath Axis selenium web driver

1. Parent Axis XPath:

With the help of the parent axis XPath, we can select the parent of the current node. Here, the parent node can be either a root node or an element node. The point to consider here is that for all the other element nodes the maximum node the parent axis contains is one. Also, the root node of the HTML DOM structure has no parent hence the parent axis is empty when the current node is the root node. 

Syntax:

Xpath = //tagname[@attribute=’value’]//parent::parent_tagname

Example:

//input[@name=’username’]//parent::div

This Screenshot is about Parent Axis Xpath

2. Child Axis XPath:

As we have seen using the parent axis XPath actually we are creating an XPath by the following bottom-up approach but here in the child axis case, we are going to follow the top-down approach to create an XPath. The child axis selects all the child elements present under the current node. We can easily locate a web element as a child of the current node. 

Syntax:

Xpath = //tagname[@attribute=’value’]//child::child_tagname

Example:

//div[@class=’oxd-form-actions orangehrm-login-action’]//child::button

The child axis selects all the child elements present under the current node. We can easily locate a web element as a child of the current node. 

3. Self Axix XPath:

This type of XPath uses its own current node and selects the web element belonging to that current node. You will always observe only one node that represents the self-web element. The tag name we provide at the start and at the end of XPath are the same as they are on the self-axis of the current node. However, this provides the confirmation of the element present when there is more than one element present having the same value and attribute. 

Syntax:

Xpath = //tagname[@attribute=’value’]//self::self_tagname

Example:

//input[@name=’username’]//self::input

This type of XPath uses its own current node and selects the web element belonging to that current node. You will always observe only one node that represents the self-web element.

4. Descendant Axis XPath:

It selects all the descendants i.e. child and grandchild of the current node. 

Syntax:

Xpath = //tagname[@attribute=’value’]//descendant::child or grandchild_tagname

Example:

//div[@class=’oxd-form-row’]//descendant::input[@name=’username’]

Username and Password
It selects all the descendants i.e. child and grandchild of the current node.

5. Descendant-or-self Axis XPath:

Using this axis we can select the current node and all its descendants i.e. child, grandchild, etc just like a descendant axis. The point to be noticed here is the tag name for descendants and self are the same. 

Syntax: 

Xpath = //tagname[@attribute=’value’]//descendant-or-self::tagname

Example:

//input[@name=’username’]//descendant-or-self::input

Using this axis we can select the current node and all its descendants i.e. child, grandchild, etc just like a descendant axis. The point to be noticed here is the tag name for descendants and self are the same. 

6. Ancestor Axis:

As we understand how the descendant axis works now, the ancestor axis works exactly opposite to that of the descendant axis. It will select or locate all ancestors elements i.e. parent, grandparent, etc of the current node. This axis contains the root node too. 

Syntax:

Xpath = //tagname[@attribute=’value’]//ancestor::ancestor_tagname

Example:

//input[@name=’username’]//ancestor::div[@class=’oxd-form-row’]

7. Ancestor-or-self Axis XPath:

Now, just like the descendant-or-self axis, the ancestor-or-self axis XPath will locate a web element having the same starting and ending tag name. 

Syntax:

Xpath = //tagname[@attribute=’value’]//ancestor-or-self::tagname

Example:

//input[@name=’username’]//ancestor-or-self::input

Now, just like the descendant-or-self axis, the ancestor-or-self axis XPath will locate a web element having the same starting and ending tag name.

8. Following Axis Path:

The following axis XPath selects all the web element that comes after the current node. 

Syntax:

Xpath = //tagname[@attribute=’value’]//following::following_tagname

Example:

//div[@class=’oxd-form-actions orangehrm-login-action’]//following::button

The following axis XPath selects all the web element that comes after the current node. 

9. Following-sibling Axis XPath

Using the following sibling axis method we can select all the nodes that have the same parent as that of the current node and that appear after the current node. 

Syntax:

Xpath = //tagname[@attribute=’value’]//following-sibling::following_tagname

Example:

//div[@class=’oxd-form-actions orangehrm-login-action’]//following-sibling::button

Using the following sibling axis method we can select all the nodes that have the same parent as that of the current node and that appear after the current node. 

10. Preceding Axis XPath

Using this axis method we can locate a web element that has the node that appears before the current node. 

Syntax:

Xpath = //tagname[@attribute=’value’]//preceding::tagname

Example:

//div[@class=’oxd-form-actions orangehrm-login-action’]//preceding::button

Example of Preceding Axis Xpath with username and Password
Using this axis method we can locate a web element that has the node that appears before the current node. 

11. Preceding-sibling Axis XPath:

Using the following sibling axis method we can select all the nodes that have the same parent as that of the current node and that appear before the current node. It works opposite to that of the following sibling axis XPath. 

Syntax:

Xpath = //tagname[@attribute=’value’]//preceding::tagname

Example:

//div[@class=’oxd-form-actions orangehrm-login-action’]//preceding::button

Example of Preceding-sibling Axis Xpath
Using the following sibling axis method we can select all the nodes that have the same parent as that of the current node and that appear before the current node. It works opposite to that of the following sibling axis XPath.

You can try all of these examples mentioned above with the Orange HRM Demo website here.

Conclusion:

In conclusion, XPath is an essential tool for web automation testing when using Selenium, Playwright, and Cypress. It allows for more flexibility and specificity in locating elements on a web page. Understanding the different types of XPath expressions and how to use them can greatly improve the efficiency and effectiveness of the automation testing process. It can be particularly useful in situations where elements do not have unique CSS selectors, or when the structure of the HTML changes frequently. With the knowledge of XPath, you can write more robust and stable automation tests.

Read more blogs here.

Single Sign On with Multi Factor Authentication using Cypress 10

Single Sign On with Multi Factor Authentication using Cypress 10

Introduction:

With Cypress 10 we can automate  Single Sign On with Multi-Factor Authentication enabled. The new feature of Cypress 10 helps us to visit multi-domain in a single test. Now the cy.origin module helps us to do the same. We can visit the Single Sign-On site and make users authenticate and redirect to our main application domain. But usually, people find it difficult to automate Single Sign On-based applications and have multi-factor authentication for security. This Blog will help us to overcome both the challenges of Single Sign On with Multi-Factor Authentication using Cypress 10 and using a session that will make our test fast, saves time of login, and authenticate once login multiple times.

Test Goal: Automate Office 365 using Cypress 10

To Overcome both the challenges of SSO and the MFA  using Cypress 10 and using session.

What are the test requirements?

  1. Cypress 10 installed.
  2. The secret key for Office 365 account.
  3. And one npm package.

Let’s start the recipe.

How do I get a secret key for an office 365 account to generate OTP:

6th Choose the authenticator app option

7th Click on the link I want to use a different authenticator app 

8th Click on next

9th Click on the button can’t scan the image

10th Copy the secret key and paste it and click on next.

Installing NPM packages required using one of the below methods:-

  • npm i -D cypress-OTP
  • yarn add -D cypress-OTP

Single Sign On with Multi-Factor Authentication using Cypress 10

We are all set for the next steps now next part is in VS code

Open VS code 

Solution:

Go to supports/command.js

  • This is a custom command, we can use this command anywhere in the cypress test. We have to add parameters such as name, Email id, password, and token as a secret which we extracted for office 365 accounts. “login” is the command name we can use using cy.login()in our test.
Cypress.Commands. add("login", (email, password, token, path) => {
  const args = { email, password, token }
  • Visit the application URL
cy.visit(Cypress.config('apiLoginURL')) 
  cy.on('uncaught:exception', (err, runnable) => {
    return false
  })
  cy.wait(7000)
  • Here we have to click on the button which navigates us to the office 365 pages where we have to authenticate the user. This landed us on the office365 SSO page. 
cy.get('.microsoft').click()
  • The new feature for Cypress 10 is cy.origin which helps us navigate to multi-domain in the same test. Here we will pass the login URL for office 365.
 cy.origin('https://login.microsoftonline.com', { args }, ({ email, password, token }) => {
    cy.wait(7000)
    cy.get('body').then(body => {
      if (body.find('#otherTileText').length > 0) {
        cy.contains('Use another account').click()
  • Passing the Email address for office 365
cy.get('#i0116').type(email)
      }
      else {
        cy.get('#i0116').type(email)
      }  
    cy.get('#idSIButton9').click()
    cy.wait(3000)
  • Passing password for office 365
cy.get('#i0118').type(password)
    cy.contains('Sign in').click()
    cy.get('div.tile:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2)').click()
  • Now we have to pass the secret key which we have extracted in the above steps and pass it to the OTP-generate task. This step is responsible for generating the secret.
 cy.task("generateOTP", token).then(token => {
      cy.get("#idTxtBx_SAOTCC_OTC").type(token);
      cy.get('#idSubmit_SAOTCC_Continue').click()
      cy.wait(3000)
    })

For any exception, we are having the below block

 cy.on('uncaught:exception', (err, runnable) => {
      return false
    })
        cy.get('#idBtn_Back').click()
        cy.wait(16000)  
        })              
}) 
})
  • Now we have to use this custom command in our test. Generally, we have to log in each time before the actual test. So we can use Cypress hooks ‘before’ and ‘before each’ hook.

Let’s see the code

Create a file and name it ‘beforeafter.js’ inside the Cypress folder. And paste the below Code

before(() => {

Here, we are creating the session

  cy.session('1', () =>{

This is a custom command we are calling in the command.js file. It passes all required parameters like email, password, and Secret key.

cy.login(Cypress.env("email"),Cypress.env("password"),Cypress.env('secret'),Cypress.env('file'))
  })   
  })
beforeEach(() => {

  Here we are restoring the above session which will help us to authenticate the user and log in quickly to the application.

cy.session('1')
cy.wait(5000)
cy.visit(Cypress.config('apiLoginURL'))
cy.get('.microsoft').click()
cy.wait(15000) 
})

Usage in test

Cypress/Support/Command.js

Cypress.Commands.add("login", (email, password, token, path) => { 
  const args = { email, password, token }
  cy.visit(Cypress.config('apiLoginURL'))
  cy.on('uncaught:exception', (err, runnable) => {
    return false
  })
  cy.wait(7000)
  cy.get('.microsoft').click() 
  cy.origin('https://login.microsoftonline.com', { args }, ({ email, password, token }) => {
    cy.wait(7000)
    cy.get('body').then(body => {
      if (body.find('#otherTileText').length > 0) {
        cy.contains('Use another account').click()
        cy.get('#i0116').type(email)
      }
      else {
        cy.get('#i0116').type(email)
      }
    cy.get('#idSIButton9').click()
    cy.wait(3000)
    cy.get('#i0118').type(password)
    cy.contains('Sign in').click()
    cy.get('div.tile:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2)').click()
    cy.task("generateOTP", token).then(token => {
      cy.get("#idTxtBx_SAOTCC_OTC").type(token);
      cy.get('#idSubmit_SAOTCC_Continue').click()
      cy.wait(3000)
    })
    cy.on('uncaught:exception', (err, runnable) => {
      return false
    })  
        cy.get('#idBtn_Back').click()
        cy.wait(16000)      
        })            
}) 
})

Usage in test

BeforeAfter.js file

before(() => {
  cy.session('1', () =>{
    cy.login(Cypress.env("email"),Cypress.env("password"),Cypress.env('secret'),Cypress.env('file'))
  })
  })
Before(() => {
  cy.session('1')
cy.wait(5000)
cy.visit(Cypress.config('apiLoginURL'))
cy.get('.microsoft').click()
cy.wait(15000)
})

Conclusion:

We are successfully able to automate login to the application through SSO and automate MFA and reduce the login time using a session in Cypress. Here is a link to another good read around the same topic.

Read more blogs here