0
0
Cypresstesting~10 mins

Dynamic response stubbing in Cypress - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - Cypress
Cypress
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');
  });
});
Execution Trace - 9 Steps
StepActionSystem StateAssertionResult
1Test starts and sets up intercept for GET /api/user with dynamic response based on userId queryCypress test runner ready with intercept active-PASS
2Browser opens and navigates to /user-profile?userId=1Page loading with userId=1 in URL-PASS
3Intercept catches GET /api/user?userId=1 and replies with {id:1, name:'Alice'}API response stubbed with Alice's data-PASS
4Test waits for @getUser request to completeAPI call completed with stubbed response-PASS
5Test finds element with data-cy=user-name and checks text contains 'Alice'User name displayed on pageAssert element text contains 'Alice'PASS
6Browser navigates to /user-profile?userId=2Page loading with userId=2 in URL-PASS
7Intercept catches GET /api/user?userId=2 and replies with {id:2, name:'Bob'}API response stubbed with Bob's data-PASS
8Test waits for @getUser request to completeAPI call completed with stubbed response-PASS
9Test finds element with data-cy=user-name and checks text contains 'Bob'User name displayed on pageAssert element text contains 'Bob'PASS
Failure Scenario
Failing Condition: The intercept does not reply with the correct stubbed data or the element selector is incorrect
Execution Trace Quiz - 3 Questions
Test your understanding
What does the intercept do in this test?
AIt always returns the same user data regardless of userId
BIt returns different user data based on the userId query parameter
CIt blocks all API requests to /api/user
DIt modifies the URL before the request is sent
Key Result
Use dynamic response stubbing to simulate different server responses based on request details, enabling thorough testing of UI behavior without relying on real backend data.