0
0
Cypresstesting~15 mins

Using fixtures in tests in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify login functionality using user data from fixture
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 explicit selectors with IDs
Use cy.visit() to open pages
Use cy.url().should() for URL assertions
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('Login Test Using Fixture', () => {
  beforeEach(() => {
    cy.visit('/login');
  });

  it('logs in using fixture data', () => {
    cy.fixture('user').then((user) => {
      cy.get('#username').type(user.username);
      cy.get('#password').type(user.password);
      cy.get('#loginBtn').click();

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

The describe block groups the login test. The beforeEach hook opens the login page before each test to ensure a fresh start.

Inside the test, cy.fixture('user') loads the user data from the user.json file. The then callback receives the user object.

We use cy.get('#username') and cy.get('#password') to find input fields by their IDs and type the fixture data into them.

Clicking the login button triggers the login action.

Finally, cy.url().should('include', '/dashboard') asserts that the URL contains '/dashboard', confirming successful login.

This approach uses best practices: clear selectors, fixture data loading, and Cypress automatic waits.

Common Mistakes - 3 Pitfalls
Hardcoding user credentials directly in the test code
Using slow fixed waits like cy.wait(5000) instead of relying on Cypress automatic waits
{'mistake': "Using vague selectors like cy.get('input') instead of specific IDs or data attributes", 'why_bad': 'Vague selectors can select wrong elements and break tests if UI changes.', 'correct_approach': 'Use unique IDs or data-cy attributes for stable selectors.'}
Bonus Challenge

Now add data-driven testing with 3 different user credentials from a fixture array

Show Hint