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.