Cypress – 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. Basically, it helps us to get the 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 the test data can be utilised by more than one test. All fixture data has to be declared within the before hook block.

Syntax

The syntax for Cypress data driven testing is as follows โˆ’

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 is the path of test data file within fixtures folder.
  • encoding type โˆ’ Encoding type (utf-8, asci, and so on) is used to read the file.
  • Opts โˆ’ Modifies the timeout for response. The default value is 30000ms. The wait time for cy.fixture(), prior throws an exception.

Implementation in example.json

Given below is the implementation of data driven testing with example.json in Cypress โˆ’

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

Implementation of Actual Test

The implementation of actual data driven testing in Cypress is as follows โˆ’

describe('Adglob.in 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)
   });
});

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

Leave a Reply