0
0
CypressHow-ToBeginner ยท 3 min read

How to Create Fixture File in Cypress for Test Data

To create a fixture file in Cypress, add a JSON file inside the cypress/fixtures folder with your test data. You can then load this data in your tests using cy.fixture('filename').then() to access the data easily.
๐Ÿ“

Syntax

Fixture files in Cypress are stored as JSON files inside the cypress/fixtures folder. You load them in your test code using cy.fixture('filename'), which returns a promise with the data.

  • filename: Name of the JSON file without the .json extension.
  • cy.fixture(): Cypress command to read the fixture file.
  • .then(): Used to access the loaded data asynchronously.
javascript
cy.fixture('user').then((userData) => {
  // use userData object here
})
๐Ÿ’ป

Example

This example shows how to create a fixture file named user.json with user details, then load and use it in a Cypress test.

javascript
// File: cypress/fixtures/user.json
{
  "name": "Alice",
  "email": "alice@example.com",
  "password": "password123"
}

// File: cypress/e2e/login.cy.js
describe('Login Test', () => {
  it('logs in using fixture data', () => {
    cy.fixture('user').then((user) => {
      cy.visit('/login')
      cy.get('#email').type(user.email)
      cy.get('#password').type(user.password)
      cy.get('button[type=submit]').click()
      cy.contains('Welcome, Alice').should('be.visible')
    })
  })
})
Output
Test passes if the login succeeds and 'Welcome, Alice' is visible on the page.
โš ๏ธ

Common Pitfalls

Common mistakes when creating or using fixture files include:

  • Placing fixture files outside the cypress/fixtures folder, so Cypress cannot find them.
  • Forgetting to remove the .json extension when calling cy.fixture().
  • Trying to use fixture data synchronously without .then(), causing undefined errors.
  • Using invalid JSON format in fixture files, which causes parsing errors.
javascript
// Wrong: Including extension
cy.fixture('user.json').then((data) => {
  // This will fail
})

// Right: Without extension
cy.fixture('user').then((data) => {
  // Works correctly
})
๐Ÿ“Š

Quick Reference

ActionSyntaxNotes
Create fixture fileAdd JSON file in cypress/fixturesUse valid JSON format
Load fixture datacy.fixture('filename')Exclude .json extension
Access datacy.fixture('filename').then((data) => {...})Use .then() for async access
Use data in testcy.get(selector).type(data.property)Use loaded data properties
โœ…

Key Takeaways

Store fixture files as JSON in the cypress/fixtures folder for easy access.
Use cy.fixture('filename') without the .json extension to load fixture data.
Always access fixture data asynchronously using .then() to avoid errors.
Ensure your fixture JSON files are valid and properly formatted.
Use fixture data to keep your tests clean and maintainable by separating test data.