0
0
Cypresstesting~5 mins

cy.fixture() for loading data in Cypress

Choose your learning style9 modes available
Introduction

We use cy.fixture() to load test data from files. This helps keep tests clean and easy to update.

When you want to reuse the same test data in many tests.
When test data is too big or complex to write inside the test code.
When you want to separate test data from test logic for clarity.
When you want to test with different sets of data without changing the test code.
Syntax
Cypress
cy.fixture('filename').then((data) => {
  // use data here
})

The filename is the name of a file in the cypress/fixtures folder.

The file can be JSON, text, or other supported formats.

Examples
This loads user.json and logs the user's name.
Cypress
cy.fixture('user.json').then((user) => {
  cy.log(user.name)
})
This loads a text file config.txt and logs its content.
Cypress
cy.fixture('config.txt').then((text) => {
  cy.log(text)
})
This saves the fixture as an alias and uses it later in the test.
Cypress
cy.fixture('data.json').as('data')

cy.get('@data').then((data) => {
  cy.log(data.value)
})
Sample Program

This test loads user.json fixture, checks if it has a name property, and verifies the name is 'Alice'. It then logs the name.

Cypress
describe('Test with fixture data', () => {
  it('loads user data from fixture', () => {
    cy.fixture('user.json').then((user) => {
      expect(user).to.have.property('name')
      expect(user.name).to.equal('Alice')
      cy.log(`User name is ${user.name}`)
    })
  })
})
OutputSuccess
Important Notes

Always put fixture files inside the cypress/fixtures folder.

Use as() to create aliases for easier reuse.

Fixtures help keep your tests clean and separate data from test steps.

Summary

cy.fixture() loads external test data files.

It helps reuse data and keeps tests simple.

Use it to separate test data from test code.