0
0
Cypresstesting~15 mins

cy.fixture() for loading data in Cypress - Build an Automation Script

Choose your learning style9 modes available
Load user data from fixture and verify login
Preconditions (2)
Step 1: Open the login page at '/login'
Step 2: Load user credentials from 'user.json' fixture
Step 3: Enter the username from fixture into the username input field with id 'username'
Step 4: Enter the password from fixture into the password input field with id 'password'
Step 5: Click the login button with id 'loginBtn'
Step 6: Verify that the URL changes to '/dashboard' after login
✅ Expected Result: User is successfully logged in and redirected to the dashboard page
Automation Requirements - Cypress
Assertions Needed:
Verify username and password fields are filled with fixture data
Verify URL is '/dashboard' after login
Best Practices:
Use cy.fixture() to load test data
Use data-driven approach by separating test data from test code
Use proper selectors (id) for locating elements
Use Cypress commands chaining and assertions
Automated Solution
Cypress
describe('Login Test with Fixture Data', () => {
  beforeEach(() => {
    cy.visit('/login');
  });

  it('should login using data from fixture', () => {
    cy.fixture('user.json').then((user) => {
      cy.get('#username').type(user.username);
      cy.get('#password').type(user.password);
      cy.get('#loginBtn').click();

      cy.url().should('include', '/dashboard');
    });
  });
});

The test starts by visiting the login page before each test.

We use cy.fixture('user.json') to load the user credentials from the fixture file.

Then we fill the username and password fields using the loaded data.

After clicking the login button, we assert that the URL includes '/dashboard' to confirm successful login.

This approach keeps test data separate and makes the test easy to maintain.

Common Mistakes - 3 Pitfalls
Hardcoding user credentials inside the test instead of using fixture
Using incorrect selectors like class names that may change frequently
Not waiting for fixture data to load before using it
Bonus Challenge

Now add data-driven testing with 3 different user credentials from separate fixture files

Show Hint