What is Fixture in Cypress: Definition and Usage
fixture is a fixed set of data stored in a file that tests can load and use. It helps keep test data separate from test code, making tests easier to read and maintain.How It Works
Think of a fixture in Cypress like a recipe card you keep in your kitchen. Instead of writing the ingredients every time you cook, you keep them ready on a card. Similarly, a fixture file holds data your tests need, like user info or settings.
When a test runs, it can "read" this fixture file and use the data inside. This keeps your test code clean and focused on actions, while the data stays organized separately. It’s like having a handy reference that your test can open anytime.
Example
This example shows how to load a fixture file named user.json and use its data in a test.
describe('User Login Test', () => { it('loads user data from fixture', () => { cy.fixture('user').then((user) => { cy.log(`Username: ${user.username}`) cy.log(`Password: ${user.password}`) // Here you could use user data to fill a login form }) }) })
When to Use
Use fixtures when you want to reuse the same test data across multiple tests or keep your test data organized outside the test code. This is helpful for:
- Loading user profiles, settings, or configurations
- Testing with different sets of data without rewriting tests
- Keeping tests clean and easy to update when data changes
For example, if you test a login feature, you can store different user credentials in fixture files and load them as needed.
Key Points
- Fixtures store static test data in files like JSON.
- They help separate data from test logic.
- Fixtures can be loaded using
cy.fixture()command. - Using fixtures improves test readability and maintenance.
Key Takeaways
cy.fixture() to load fixture data into tests.