0
0
Cypresstesting~5 mins

JSON fixture files in Cypress

Choose your learning style9 modes available
Introduction

JSON fixture files help you store test data separately from your test code. This makes tests easier to read and maintain.

When you want to reuse the same test data in multiple tests.
When you need to keep your test code clean and simple.
When you want to simulate API responses with fixed data.
When you want to separate data from test logic for better organization.
Syntax
Cypress
{
  "key": "value",
  "number": 123,
  "array": ["item1", "item2"]
}

JSON files must be valid JSON format with double quotes around keys and strings.

Save fixture files in the cypress/fixtures folder for Cypress to find them automatically.

Examples
A simple JSON fixture with username and password for login tests.
Cypress
{
  "username": "testuser",
  "password": "mypassword"
}
A JSON fixture with an array of user objects to test user lists.
Cypress
{
  "users": [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"}
  ]
}
Sample Program

This Cypress test loads user data from a JSON fixture file named user.json. It uses the data to fill in the login form and checks if the user is redirected to the dashboard.

Cypress
describe('Login Test with JSON Fixture', () => {
  beforeEach(() => {
    cy.fixture('user').then((user) => {
      cy.wrap(user).as('userData')
    })
  })

  it('logs in using fixture data', function () {
    cy.visit('/login')
    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

Always keep your JSON fixture files well formatted to avoid syntax errors.

You can load fixtures using cy.fixture() and alias them for easy access in tests.

Fixtures help keep your tests clean and make it easy to update test data without changing test code.

Summary

JSON fixture files store test data separately from test code.

Use cy.fixture() to load fixture data in Cypress tests.

Fixtures improve test readability and maintainability.