0
0
Cypresstesting~15 mins

Stubbing responses in Cypress - Build an Automation Script

Choose your learning style9 modes available
Stub API response for user data and verify UI display
Preconditions (2)
Step 1: Open the web application home page at http://localhost:3000
Step 2: Stub the GET /api/users API call to return a fixed list of users: [{id:1, name:'Alice'}, {id:2, name:'Bob'}]
Step 3: Reload the page to trigger the API call
Step 4: Verify that the user list on the page shows 'Alice' and 'Bob'
✅ Expected Result: The page displays the stubbed user names 'Alice' and 'Bob' in the user list instead of real API data
Automation Requirements - Cypress
Assertions Needed:
Verify the GET /api/users request is stubbed and called
Verify the UI displays the stubbed user names 'Alice' and 'Bob'
Best Practices:
Use cy.intercept() to stub network responses
Use alias for intercepted requests and wait for them
Use data-test attributes or semantic selectors for UI elements
Avoid hardcoded waits; use Cypress commands for synchronization
Automated Solution
Cypress
describe('User list with stubbed API response', () => {
  it('should display stubbed users Alice and Bob', () => {
    cy.intercept('GET', '/api/users', {
      statusCode: 200,
      body: [
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' }
      ]
    }).as('getUsers')

    cy.visit('http://localhost:3000')

    cy.wait('@getUsers')

    cy.get('[data-test=user-list]').should('contain.text', 'Alice')
    cy.get('[data-test=user-list]').should('contain.text', 'Bob')
  })
})

This test uses cy.intercept() to stub the GET request to /api/users. We provide a fixed response with two users, Alice and Bob.

We give this intercept an alias @getUsers so we can wait for it to complete with cy.wait(). This ensures the page has received the stubbed data before we check the UI.

We visit the page URL to trigger the API call. Then we check the user list element (selected by data-test=user-list) contains the names Alice and Bob.

This approach avoids flaky tests by synchronizing on the network call and uses semantic selectors for maintainability.

Common Mistakes - 3 Pitfalls
{'mistake': 'Using cy.wait(500) instead of waiting for the stubbed request', 'why_bad': 'Fixed waits can cause flaky tests if the network is slower or faster. It wastes time or causes failures.', 'correct_approach': "Use cy.wait('@alias') to wait for the intercepted request to complete."}
{'mistake': 'Not using an alias for the intercepted request', 'why_bad': 'Without an alias, you cannot wait for the request or verify it was called, reducing test reliability.', 'correct_approach': "Assign an alias with .as('name') and use cy.wait('@name') to synchronize."}
Selecting UI elements by brittle CSS selectors or XPath
Bonus Challenge

Now add data-driven testing with 3 different stubbed user lists and verify the UI for each

Show Hint