Read CSV Data In Cypress

Anshita Bhasin
7 min readAug 2, 2023

--

Reading CSV data is required when you have a large number of data entries that need to be used in your tests or scenarios. Manually writing and managing test data for each data entry can be time-consuming and error-prone, especially when dealing with a large dataset.

By using CSV files to store your test data, you can simplify the process of managing and maintaining test data for different test cases.

Here’s why reading CSV data becomes important in such scenarios:

  1. Handling Multiple Test Data Entries: When you have a large number of test cases or scenarios that require different sets of data, maintaining this data manually becomes impractical. Storing the data in a CSV file allows you to organize and manage all the test data entries efficiently.
  2. Test Data Reusability: Using a CSV file enables you to reuse the same data for multiple test cases. This reusability can significantly reduce duplication of efforts in creating test data for similar scenarios.
  3. Easy Data Modification: Editing a CSV file is simple and straightforward, especially when compared to updating hardcoded test data within test scripts. If there are changes in the test data, you can easily modify the CSV file without altering the test code.
  4. Data Independence: Keeping the test data separate from the test scripts ensures that your tests are not tightly coupled with the data. This separation enhances maintainability and allows you to swap or update the data without affecting the test logic.

In this blog, we will learn how to read data from CSV in Cypress.

Step1 : Install Neat-CSV

Go to the terminal and paste the below code

npm install neat-csv@v5.2.0

Once, it is installed. You would see a dependency added to the package.json, just like shown below:

Step 2: Create a sample CSV File

Let’s understand the flow with the sample example where I will automate a registration form for 5 different users and fetch the data from a CSV file.

Registration Form

Let’s generate a sample CSV file for the registration form.

The above form consists of six input fields. We will create a CSV file with five columns, as the password and confirm password can be fetched from a single field.

firstName,lastName,Email,Telephone,Password
Tom,QA,tom.qa@dispostable.com,123344590,Cypress123!!
Peter,QA,peter.qa@dispostable.com,123344590,Cypress123!!
Ally,QA,ally.qa@dispostable.com,123344590,Cypress123!!
Hiya,QA,hiya.qa@dispostable.com,123344590,Cypress123!!
AB,QA,AB.qa@dispostable.com,123344590,Cypress123!!

Create a .csv file inside the fixtures folder just like shown below and paste the above data.

Step3: Import CSV in the test file and start writing the test case

Below is the sample code for automating the registration flow for 5 users.


import { faker } from '@faker-js/faker';
const csv = require('neat-csv')

let regData

describe('Registration Form', () => {
before(() => {
cy.fixture("users.csv")
.then(csv)
.then((data) => {
regData = data
})
})

it(' Fill Reg Form for different users ', () => {
for (let i = 0; i < regData.length; i++) {
cy.visit('')
cy.get('#input-firstname').type(regData[i]['firstName']);
cy.get('#input-lastname').type(regData[i]['lastName']);
cy.get('#input-email').type(faker.datatype.uuid() + regData[i]['Email']);
cy.get('#input-telephone').type(regData[i]['Telephone']);
cy.get('#input-password').type(regData[i]['Password']);
cy.get('#input-confirm').type(regData[i]['Password']);
cy.get('input[type="checkbox"]').check()
cy.get('input.btn.btn-primary').click()
cy.get('a[data-toggle="dropdown"]').first().click()
cy.contains('Logout').click()
}

})

})

Code Walkthrough

  1. Import faker API
import { faker } from '@faker-js/faker';

The import statement above allows us to access the diverse methods provided by Faker.js using the faker object. I have used the Faker API in the code because the registration email requires uniqueness. To achieve this, I used the Faker.js library to generate random data each time, ensuring distinct email addresses for the registration process.

2. Require ‘neat-csv’ Module:

const csv = require('neat-csv')javascriptCopy code

This above code imports the ‘neat-csv’ module, which helps parse the CSV data into a readable format.

2. Declare ‘regData’ Variable:

let regData

The regData variable is declared to store the parsed CSV data.

3. Describe the Test Suite for the ‘Registration Form’:

describe('Registration Form',()=>{

The describe function creates a test suite named 'Registration Form.' Test suites group related test cases together for better organization and readability.

4. Use ‘before’ Hook to Read CSV Data:

before(() => {
cy.fixture("users.csv")
.then(csv)
.then((data) => {
regData = data
})
})
  • The before hook runs before any test cases in the test suite. In this case, it reads the 'users.csv' file using cy.fixture.
  • The then(csv) part of the code parses the CSV data using the 'neat-csv' module and converts it into an array of objects.
  • The parsed data is then stored in the regData variable, making it accessible in the subsequent test case.

Please note, our csv file is inside fixture folder. That’s why we have cy.fixture() in the above code. The folder structure is as below :

5. Define the Test Case for Filling the Registration Form:

it(' Fill Reg Form for different users ', () => {
  • The it function defines a test case titled 'Fill Reg Form for different users.'

6. Loop through CSV Data and Fill the Form:

        for (let i = 0; i < regData.length; i++) 
{
cy.visit('')
cy.get('#input-firstname').type(regData[i]['firstName']);
cy.get('#input-lastname').type(regData[i]['lastName']);
cy.get('#input-email').type(faker.datatype.uuid() + regData[i]['Email']);;
cy.get('#input-password').type(regData[i]['Password']);
cy.get('#input-confirm').type(regData[i]['Password']);
cy.get('input[type="checkbox"]').check()
cy.get('input.btn.btn-primary').click()
cy.get('a[data-toggle="dropdown"]').first().click()
cy.contains('Logout').click()
}

The above code uses a for loop to iterate through each data entry in the 'regData' array, which contains the parsed CSV data.

  • Inside the loop, the test visits the registration form page with cy.visit(‘’) command (The URL is mentioned in Cypress.config.js)

For interacting with the elements on the page, we are using cy.get() and cy.get().type() command.

cy.get(‘#input-firstname’).type(regData[i][‘firstName’]);

  • cy.get('#input-firstname'): This command selects the HTML element with the ID "input-firstname." It targets the input field where users can enter their first name on the registration form.
  • .type(regData[i]['firstName']): The .type() command simulates user typing and inputs the value of regData[i]['firstName'] into the selected input field.

At the start of the code, we have implemented a loop. With each iteration of the loop, we access and use the “firstName” data from the specific row being processed. Here, the variable “i” is used as an iterator to represent the current row in the loop.

Likewise, for the other fields as well, the code selects the HTML element using the provided locator and proceeds to input the corresponding test data from the CSV file.

Except for email entering, a different approach is taken as the email address on the registration form is unique. To address this, I have used the faker API.

Below is the sample code to enter the randomly generated email with fixed suffix value (which we are fetching from CSV file )

cy.get('#input-email').type(faker.datatype.uuid() + regData[i]['Email']);

faker.datatype.uuid(): This method from the faker API generates a random UUID which is unique across all devices and systems and is randomly generated every time this method is called.

regData[i]['Email']: This part of the code accesses the email value from the current data entry in the regData array. The variable i represents the current iteration of the loop, allowing us to access the specific email value for the current user.

faker.datatype.uuid() + regData[i]['Email']: We concatenate the generated UUID with the email address from regData[i]['Email'], creating a unique email address for the current registration form submission.

Finally, the code uses cy.get('#input-email') to select the email input field on the registration form. It then uses .type() to enter the concatenated unique email value into the email input field, ensuring a distinct email address is used for each registration form submission.

Execution

In the above screenshot, we can clearly see we are fetching data from a CSV file. Notably, for the Email field, the prefix is randomly generated using the Faker API.

This approach ensures that each email address used during the registration process is unique and dynamically generated, making the test more robust and realistic.

Conclusion:

In conclusion, reading CSV data in Cypress (or any other testing framework) is essential when dealing with a large number of data entries. It simplifies the process of managing and using test data, enhances test data reusability, and improves collaboration among team members. By adopting this approach, you can efficiently handle large datasets and maintain a robust and reliable testing process for your web applications.

Thanks for reading. Happy learning — AB!

Thanks, Naveen AutomationLabs for the guidance.

Ref — https://www.npmjs.com/package/@faker-js/faker, https://npm.io/package/neat-csv

Practice website — https://naveenautomationlabs.com/opencart/index.php?route=account/register

Git Code: https://github.com/Anshita-Bhasin/Cypress_Read_Data_From_CSV

Anshita Bhasin
QA Chapter Lead

GitHub | LinkedIn | Twitter | Youtube

--

--

Anshita Bhasin

QA Chapter Lead at Proptech company in Dubai.. Here to share and learn new things! Youtube => ABAutomationHub