06 Cypress Fixture - biswajitsundara/Cypress GitHub Wiki

  • Fixtures are the files containing data to be consumed in the spec files.
  • Cypress has default the folder fixtures and all the data files should be kept here
  • We can also create sub folders under fixtures to organize our test data
  • We can place any file type JSON (most popular), CSV, txt, png, java script, html files etc
  • When we mention the file name in fixture, no need to mention the file extension
  • It automatically searches for the file under fixture folder and picks the file that matches the name.

Create the file

cypress/fixtures/credentials.json

{
  "email": "[email protected]",
  "password": "automation"
}

The Spec File

/// <reference types="cypress" />

describe('Fixture Test Suite', () => {

    it('Basic practice website', () => {

        cy.visit("http://automationpractice.com/index.php?controller=authentication&back=my-account");
        cy.fixture('credentials').then((user)=>{

        cy.get('#email').type(user.email);
        cy.get('#passwd').type(user.password);
        cy.get('#SubmitLogin').click();

        })
        
    })
})

Fixture & Hooks

If we have multiple tests consuming the data then we can put the fixture block in the before each method. I always recommend even though there are no multiple tests, we can place the fixture part in before block so that it reads the data before the test execution and our test block contains only codes related to the test flow.

/// <reference types="cypress" />

describe('Fixture Test Suite', () => {

    let testdata;
    
    before(function () {
        cy.fixture('credentials').then((data) => {
            testdata=data;
        })
    })

    it('Basic practice website', () => {
        cy.visit("http://automationpractice.com/index.php?controller=authentication&back=my-account");
        cy.get('#email').type(testdata.email);
        cy.get('#passwd').type(testdata.password);
        cy.get('#SubmitLogin').click();
    })

})

How to Read/Write to Files

cy.writeFile('Sample.txt','Hello World');
cy.writeFile('Sample.txt','I am Biswajit',{flag:'a+'});   
cy.readFile('Sample.txt').should('contains','Hello World');
  • If we set the flag a+ then it will append to the file, else it will overwrite the file.
  • The exact file path needs to be given, my files are under root folder so I have just given the file name
  • Unlike fixtures, we will have to mention the file extension else it won't work.
⚠️ **GitHub.com Fallback** ⚠️