Open In App

Cypress - Data Driven Testing

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cypress is an open-source website testing tool that automates tests for JavaScript web applications. It is designed for end-to-end testing and can be used for unit and integration tests. It is fast, reliable, and can run directly in the browser in real-time.

It’s built to work with any front-end framework or website, including React, Angular, and Vue. In this article, we will learn about data-driven testing in Cypress.

What is Data-Driven Testing?

Data-driven testing is a concept in which we separate test data from test login. Test data is stored externally and loaded into test scripts during runtime. This allows you to run the same test with multiple data sets. In Cypress Data Driven testing is possible using the fixtures feature.

Benefits of Data-Driven Testing

  • Test scripts can be reused with different structures of data sets.
  • It becomes easier to modify the data sets.
  • allows you to test with a large volume of data sets.
  • ensures consistency in testing by using predefined data sets.

Best Practices of Data-Driven Testing

  • You can store your test data in well-structured files like JSON, or CSV within a designated directory.
  • You can load the test data once using fixtures and reuse it across multiple tests.
  • Write modular and independent tests that can run with different data sets without dependencies.
  • Ensure that each test cleans up after itself, especially when dealing with stateful operations like logging in and out.

Pre-Requisites of Data-Driven Framework in Cypress

Installation

Before we begin make sure node.js is installed in your system. Open the Windows Command Prompt, Powershell or a similar command line tool, and type:

node -v

Step 1: Create a Project Folder and move to it by using the following command.

mkdir cypress cd cypress

Step 2: Initialize a project and Install Cypress.

npm init -y
npm install cypress –save-dev

Step 3: After Creating a Project, Run this command to start cypress.

npx cypress open

Step 4: Testing type, Configuration and creating a spec.

  • Choose a E2E Testing or Component Testing, then after quick configuration choose browser.
  • After that create a new spec then click on your spec name to open your spec in any IDE.

Step 5: Testing HTML File.

  • Create a HTML File and open it with any live server extension.
  • copy that live server file serve link, for later use.

Step 6: Prepare Data

Before we start, Create a loginData.json file inside cypress/fixtures/ folder and add the below data.

{
"incorrectUsername": "wrongUser",
"incorrectPassword": "wrongPass",
"correctUsername": "correctUser",
"correctPassword": "correctPass"
}

Folder Structure

data-driven-folder-structure

Example of Data Driven Testing

The below example demonstrate the Fixture in Cypress

Create and Run HTML File and Cypress Script:

HTML
<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Login Form</title>
</head>
<body>
  <h1>Login</h1>
  <form id="loginForm">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username">
    <br><br>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password">
    <br><br>
    <button type="button" id="loginButton" disabled>Login</button>
  </form>
  <p id="errorMessage" style="display: none; color: red;">Invalid credentials</p>
  <p id="welcomeMessage" style="display: none;">Welcome, <span id="user"></span>!</p>

  <script>
    document.getElementById('username').addEventListener('input', enableButton);
    document.getElementById('password').addEventListener('input', enableButton);

    function enableButton() {
      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;
      document.getElementById('loginButton').disabled = !(username && password);
    }

    document.getElementById('loginButton').addEventListener('click', () => {
      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;
      if (username === 'correctUser' && password === 'correctPass') {
        document.getElementById('welcomeMessage').style.display = 'block';
        document.getElementById('user').textContent = username;
        document.getElementById('errorMessage').style.display = 'none';
      } else {
        document.getElementById('errorMessage').style.display = 'block';
        document.getElementById('welcomeMessage').style.display = 'none';
      }
    });
  </script>
</body>
</html>
JavaScript
// gfg.cy.js

describe('Login Form Functionality', function (){
  beforeEach(function(){
    cy.fixture('loginData.json').then((data) => {
      this.data = data;
    });
  });

  it('should verify the login form elements and functionality', function(){
    // 1. Visit the login page
    cy.visit('http://127.0.0.1:5500/index.html');

    // 2. Verify the presence and visibility of the login form elements
    cy.get('#username').should('exist').and('be.visible');
    cy.get('#password').should('exist').and('be.visible');
    cy.get('#loginButton').should('exist').and('be.visible');

    // 3. Verify that the login button is initially disabled
    cy.get('#loginButton').should('be.disabled');

    // 4. Enter an incorrect username and password
    cy.get('#username').type(this.data.incorrectUsername);
    cy.get('#password').type(this.data.incorrectPassword);
    cy.get('#loginButton').should('be.enabled').click();

    // 5. Verify error message is displayed
    cy.get('#errorMessage').should('exist').and('be.visible').and('contain', 'Invalid credentials');

    // 6. Enter a correct username and password
    cy.get('#username').clear().type(this.data.correctUsername);
    cy.get('#password').clear().type(this.data.correctPassword);
    cy.get('#loginButton').click();

    // 7. Verify the welcome message is displayed and contains the correct username
    cy.get('#welcomeMessage').should('exist').and('be.visible').and('contain', `Welcome, ${this.data.correctUsername}`);
    cy.get('#errorMessage').should('not.be.visible');
  });
});

Output

Conclusion

Cypress is a end-to-end automated testing tool that enables efficient and reliable testing of web applications. It provides Fixtures to Load the fix data sets. By following this article, you can learn to implement data driven testing in cypress. Cypress commands are easy-to-write that make it an ideal choice for automating the testing of web components.


Next Article

Similar Reads