0
0
Cypresstesting~15 mins

Dynamic response stubbing in Cypress - Build an Automation Script

Choose your learning style9 modes available
Stub API response dynamically based on request parameter
Preconditions (3)
Step 1: Visit the page at http://localhost:3000
Step 2: Intercept the GET request to /api/user?id=1 and stub the response with user name 'Alice'
Step 3: Click the button with id 'load-user'
Step 4: Verify the page displays the user name 'Alice'
Step 5: Intercept the GET request to /api/user?id=2 and stub the response with user name 'Bob'
Step 6: Click the button with id 'load-user' again after changing the userId parameter to 2
Step 7: Verify the page displays the user name 'Bob'
✅ Expected Result: The page shows 'Alice' after the first click and 'Bob' after the second click, confirming dynamic stubbing based on request parameters.
Automation Requirements - Cypress
Assertions Needed:
Verify the displayed user name matches the stubbed response
Verify the correct API endpoint with query parameter is intercepted
Best Practices:
Use cy.intercept with a function to dynamically stub responses based on request query
Use aliases for intercepted routes
Use Cypress commands for clicking and assertions
Avoid hardcoding waits; rely on Cypress automatic waits
Automated Solution
Cypress
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.

Common Mistakes - 3 Pitfalls
Hardcoding the stub response without checking request parameters
{'mistake': 'Using cy.wait with fixed time instead of waiting for intercepted request alias', 'why_bad': 'Fixed waits slow down tests and can cause flaky results if the network is slow or fast.', 'correct_approach': "Use cy.wait('@alias') to wait for the specific intercepted request to complete."}
{'mistake': 'Not using aliases for intercepted routes', 'why_bad': "Without aliases, it's harder to wait for or reference specific network calls in tests.", 'correct_approach': 'Always assign an alias to intercepted routes for better control and readability.'}
Bonus Challenge

Now add data-driven testing with 3 different userIds (1, 2, 3) and verify the displayed user names or error message accordingly.

Show Hint