0
0
Cypresstesting~10 mins

Stubbing responses in Cypress - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test stubs a network response for a user API call and verifies the UI shows the stubbed user name.

Test Code - Cypress
Cypress
describe('User API stub test', () => {
  it('stubs the /api/user response and checks UI', () => {
    cy.intercept('GET', '/api/user', { fixture: 'user.json' }).as('getUser');
    cy.visit('/profile');
    cy.wait('@getUser');
    cy.get('[data-cy=user-name]').should('contain.text', 'John Doe');
  });
});
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1cy.intercept stubs GET /api/user with fixture user.json and aliases it as getUserNo browser interaction yet, stub is ready-PASS
2cy.visit navigates to /profile pageBrowser loads /profile page, triggers GET /api/user request-PASS
3cy.wait waits for the aliased getUser network call to completeStubbed response from user.json is returned instead of real APIVerify network call intercepted and stubbed response receivedPASS
4cy.get finds element with data-cy=user-name and checks its textPage shows user name from stubbed responseAssert element text contains 'John Doe'PASS
Failure Scenario
Failing Condition: The stub fixture file user.json is missing or malformed, or the selector [data-cy=user-name] does not exist on the page
Execution Trace Quiz - 3 Questions
Test your understanding
What does cy.intercept do in this test?
AIt replaces the real API response with a stubbed fixture
BIt navigates to the profile page
CIt waits for the network call to finish
DIt checks the text of an element
Key Result
Stubbing network responses isolates tests from backend changes and makes UI tests faster and more reliable.