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.jsonextension.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/fixturesfolder, so Cypress cannot find them. - Forgetting to remove the
.jsonextension when callingcy.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
| Action | Syntax | Notes |
|---|---|---|
| Create fixture file | Add JSON file in cypress/fixtures | Use valid JSON format |
| Load fixture data | cy.fixture('filename') | Exclude .json extension |
| Access data | cy.fixture('filename').then((data) => {...}) | Use .then() for async access |
| Use data in test | cy.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.