How to perform data-driven testing in Cypress?


Cypress data-driven testing is achieved with the help of fixtures. Cypress fixtures are added to maintain and hold the test data for automation. The fixtures are kept inside the fixtures folder (example.json file) in the Cypress project. It basically helps us to get data input from external files.

Cypress fixtures folder can have files in JSON or other formats and the data is maintained in "key:value" pairs. All these test data can be utilized by more than one test. All fixture data has to be declared within the before hook block.

Syntax

cy.fixture(path of test data)
cy.fixture(path of test data, encoding type )
cy.fixture(path of test data, opts)
cy.fixture(path of test data, encoding type , options)

Here,

path of test data – path of test data file within fixtures folder

encoding type – encoding type(utf-8, asci, and so on) used to read the file.

opts – modifies the timeout for a response. The default value is 30000ms. The wait time for cy.fixture() prior throws an exception.

Example

Implementation in example.json

{
   "fullName": "Robert",
   "number": "789456123"
}

Implementation of Actual Test

describe('Tutorialspoint Test', function () {
   //part of before hook
   before(function(){
      //access fixture data
      cy.fixture('example').then(function(regdata){
         this.regdata=regdata
      })
   })
   // test case
   it('Test Case1', function (){
      // launch URL
      cy.visit("https://register.rediff.com/register/register.php")
      //data driven from fixture
      cy.get(':nth-child(3) > [width="185"] > input')
      .type(this.regdata.fullName)
      cy.get('#mobno').type(this.regdata.number)
   });
});

Execution Results

The output logs show the values Robert and 789456123 being fed to the Full Name and Mobile No. fields respectively. These data have been passed to the test from the fixtures.

Updated on: 19-Nov-2021

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements