describe('Dynamic response stubbing test', () => {
beforeEach(() => {
cy.visit('http://localhost:3000');
});
it('stubs API response dynamically based on userId query parameter', () => {
cy.intercept('GET', '/api/user*', (req) => {
const userId = req.query.id;
if (userId === '1') {
req.reply({ statusCode: 200, body: { name: 'Alice' } });
} else if (userId === '2') {
req.reply({ statusCode: 200, body: { name: 'Bob' } });
} else {
req.reply({ statusCode: 404, body: { error: 'User not found' } });
}
}).as('getUser');
// Trigger first request with userId=1
cy.get('#load-user').click();
cy.wait('@getUser');
cy.contains('Alice').should('be.visible');
// Change userId to 2 in the app before clicking again
// Assuming there's a way to set userId, e.g., input field with id 'user-id'
cy.get('#user-id').clear().type('2');
cy.get('#load-user').click();
cy.wait('@getUser');
cy.contains('Bob').should('be.visible');
});
});This test visits the page before each test run to start fresh.
We use cy.intercept with a function to check the id query parameter dynamically. Based on the userId, we reply with different stubbed user names.
The alias @getUser helps us wait for the API call to complete before asserting the page content.
We simulate clicking the button to load user data for userId=1 and verify the page shows 'Alice'. Then we change the userId input to '2', click again, and verify the page shows 'Bob'.
This approach ensures dynamic response stubbing based on request parameters, making tests flexible and realistic.