Test Overview
This test uses Cypress to stub a dynamic API response based on the request query parameter. It verifies that the page displays the correct user name from the stubbed response.
This test uses Cypress to stub a dynamic API response based on the request query parameter. It verifies that the page displays the correct user name from the stubbed response.
describe('Dynamic response stubbing test', () => { it('stubs API response dynamically based on userId', () => { cy.intercept('GET', '/api/user*', (req) => { const userId = req.query.userId; if (userId === '1') { req.reply({ statusCode: 200, body: { id: 1, name: 'Alice' } }); } else if (userId === '2') { req.reply({ statusCode: 200, body: { id: 2, name: 'Bob' } }); } else { req.reply({ statusCode: 404, body: { error: 'User not found' } }); } }).as('getUser'); cy.visit('/user-profile?userId=1'); cy.wait('@getUser'); cy.get('[data-cy=user-name]').should('contain.text', 'Alice'); cy.visit('/user-profile?userId=2'); cy.wait('@getUser'); cy.get('[data-cy=user-name]').should('contain.text', 'Bob'); }); });
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and sets up intercept for GET /api/user with dynamic response based on userId query | Cypress test runner ready with intercept active | - | PASS |
| 2 | Browser opens and navigates to /user-profile?userId=1 | Page loading with userId=1 in URL | - | PASS |
| 3 | Intercept catches GET /api/user?userId=1 and replies with {id:1, name:'Alice'} | API response stubbed with Alice's data | - | PASS |
| 4 | Test waits for @getUser request to complete | API call completed with stubbed response | - | PASS |
| 5 | Test finds element with data-cy=user-name and checks text contains 'Alice' | User name displayed on page | Assert element text contains 'Alice' | PASS |
| 6 | Browser navigates to /user-profile?userId=2 | Page loading with userId=2 in URL | - | PASS |
| 7 | Intercept catches GET /api/user?userId=2 and replies with {id:2, name:'Bob'} | API response stubbed with Bob's data | - | PASS |
| 8 | Test waits for @getUser request to complete | API call completed with stubbed response | - | PASS |
| 9 | Test finds element with data-cy=user-name and checks text contains 'Bob' | User name displayed on page | Assert element text contains 'Bob' | PASS |