0
0
Cypresstesting~5 mins

Using fixtures in tests in Cypress

Choose your learning style9 modes available
Introduction

Fixtures help you use fixed data in your tests. This makes tests simple and repeatable.

When you want to load user data like names and emails for testing forms.
When you need to reuse the same data in many tests without rewriting it.
When you want to separate test data from test code for clarity.
When you want to test how your app handles specific data sets.
When you want to mock API responses with static data.
Syntax
Cypress
cy.fixture('filename').then((data) => {
  // use data here
})

Put your fixture files in the cypress/fixtures folder.

Fixture files are usually JSON but can be other formats like text or CSV.

Examples
This loads user.json and types the user's name into a form field.
Cypress
cy.fixture('user.json').then((user) => {
  cy.get('input[name="username"]').type(user.name)
})
This loads settings.json once before each test and uses it with this.settings.
Cypress
beforeEach(() => {
  cy.fixture('settings.json').as('settings')
})

it('uses settings', function() {
  cy.log(this.settings.theme)
})
Sample Program

This test loads user data from user.json fixture. It fills the login form and checks if the URL changes to dashboard after submit.

Cypress
describe('Login form test', () => {
  beforeEach(() => {
    cy.visit('/login')
    cy.fixture('user.json').as('userData')
  })

  it('fills and submits login form', function() {
    cy.get('input[name="username"]').type(this.userData.username)
    cy.get('input[name="password"]').type(this.userData.password)
    cy.get('button[type="submit"]').click()
    cy.url().should('include', '/dashboard')
  })
})
OutputSuccess
Important Notes

Use .as() to alias fixture data for easy access with this.

Fixtures keep your tests clean by separating data from test steps.

Always check fixture file paths and names carefully to avoid loading errors.

Summary

Fixtures store fixed test data outside test code.

Load fixtures with cy.fixture() and use the data in tests.

Fixtures make tests easier to read and maintain.