0
0
Cypresstesting~15 mins

Fixture-based response mocking in Cypress - Build an Automation Script

Choose your learning style9 modes available
Mock API response using fixture in Cypress
Preconditions (3)
Step 1: Open the application page that triggers the GET request to '/api/user'
Step 2: Intercept the GET request to '/api/user' and respond with the fixture 'user.json'
Step 3: Verify that the UI displays the user data from the fixture
✅ Expected Result: The UI shows user information exactly as defined in the 'user.json' fixture file, confirming the API response was mocked successfully.
Automation Requirements - Cypress
Assertions Needed:
Verify the GET request to '/api/user' is intercepted and responded with fixture data
Verify the UI displays user name and email from the fixture
Best Practices:
Use cy.intercept() with fixture option to mock API response
Use alias for intercepted request and wait for it
Use data from fixture for assertions
Keep fixture files organized in cypress/fixtures folder
Automated Solution
Cypress
describe('Fixture-based response mocking test', () => {
  beforeEach(() => {
    cy.intercept('GET', '/api/user', { fixture: 'user.json' }).as('getUser');
    cy.visit('/user-profile');
  });

  it('should display user data from fixture', () => {
    cy.wait('@getUser');
    cy.fixture('user.json').then((user) => {
      cy.get('[data-cy=user-name]').should('contain.text', user.name);
      cy.get('[data-cy=user-email]').should('contain.text', user.email);
    });
  });
});

This test uses cy.intercept() to mock the GET request to /api/user with the fixture user.json. The as('getUser') creates an alias to wait for the request to complete. The test visits the user profile page, waits for the mocked API call, then loads the fixture data again to assert that the UI elements display the expected user name and email. Using data-cy attributes for selectors follows best practices for stable tests.

Common Mistakes - 3 Pitfalls
Not using alias and wait for intercepted request
Hardcoding selectors like classes or ids that may change
{'mistake': 'Not placing fixture files in the correct folder', 'why_bad': "Cypress won't find the fixture file if it's not in the <code>cypress/fixtures</code> folder, causing test errors.", 'correct_approach': 'Always keep fixture JSON files inside the <code>cypress/fixtures</code> directory.'}
Bonus Challenge

Now add data-driven testing with 3 different user fixtures to verify the UI displays each user's data correctly

Show Hint