How to Use cy.fixture in Cypress for Test Data Loading
Use
cy.fixture in Cypress to load external files like JSON for test data. It reads the file asynchronously and returns its content, which you can use in your tests with .then() or async/await.Syntax
The cy.fixture command loads a fixed set of data located in the cypress/fixtures folder. You provide the filename as a string, and it returns the file content as a JavaScript object or string.
Example parts:
cy.fixture('filename'): loads the file namedfilenamefrom the fixtures folder..then((data) => { ... }): callback to use the loaded data.
javascript
cy.fixture('example.json').then((data) => { // use data here });
Example
This example shows how to load a JSON fixture file and use its data to fill a form in a test.
javascript
describe('Using cy.fixture example', () => { it('loads user data from fixture and fills form', () => { cy.visit('https://example.cypress.io/commands/actions') cy.fixture('user.json').then((user) => { cy.get('#email1').type(user.email) cy.get('#password1').type(user.password) }) }) })
Output
Test passes if the form fields are filled with fixture data without errors.
Common Pitfalls
Common mistakes when using cy.fixture include:
- Not placing the fixture file inside the
cypress/fixturesfolder. - Forgetting that
cy.fixtureis asynchronous and trying to use data outside.then(). - Using incorrect file names or extensions.
Always use .then() or async/await to handle the loaded data properly.
javascript
/* Wrong way: trying to use fixture data outside then */ cy.fixture('user.json').then((userData) => { // userData is available here }) // Trying to use userData here will fail /* Right way: use inside then */ cy.fixture('user.json').then((userData) => { cy.get('#email1').type(userData.email) })
Quick Reference
- File location: Place fixture files in
cypress/fixtures. - Supported formats: JSON, text, CSV, etc.
- Usage:
cy.fixture('fileName').then(data => { ... }) - Async: Always handle data inside
.then()or use async/await.
Key Takeaways
Use cy.fixture to load external test data files from the fixtures folder.
Always handle fixture data asynchronously inside .then() or with async/await.
Place your fixture files correctly in cypress/fixtures with proper file names.
cy.fixture supports JSON and other text-based formats for flexible test data.
Avoid using fixture data outside the asynchronous callback to prevent errors.