0
0
Cypresstesting~10 mins

Why intercepting network validates API integration in Cypress - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test checks that when the user clicks a button, the app sends the correct API request and handles the response properly. It verifies API integration by intercepting the network call and confirming the response data is shown on the page.

Test Code - Cypress
Cypress
describe('API Integration Test with Network Intercept', () => {
  it('should fetch and display user data on button click', () => {
    cy.intercept('GET', '/api/user', {
      statusCode: 200,
      body: { id: 1, name: 'Alice' }
    }).as('getUser')

    cy.visit('/user-profile')
    cy.get('#fetch-user-btn').click()

    cy.wait('@getUser').its('response.statusCode').should('eq', 200)
    cy.get('#user-name').should('contain', 'Alice')
  })
})
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1cy.intercept sets up a stub for GET /api/user with mock responseNo page loaded yet, network intercept ready-PASS
2cy.visit opens the /user-profile page in browserUser profile page loaded with button #fetch-user-btn visible-PASS
3cy.get finds the button #fetch-user-btn and clicks itButton clicked, app triggers GET /api/user request-PASS
4cy.wait waits for the intercepted GET /api/user request to completeNetwork call intercepted, response received with status 200 and body {id:1, name:'Alice'}Check response status code equals 200PASS
5cy.get finds element #user-name and checks it contains text 'Alice'Page shows user name 'Alice' after API responseVerify UI updated with API response dataPASS
Failure Scenario
Failing Condition: API request does not return status 200 or UI does not update with user name
Execution Trace Quiz - 3 Questions
Test your understanding
What does cy.intercept do in this test?
AIt clicks the button to trigger the API call
BIt catches the API request and provides a fake response
CIt checks the text on the page
DIt opens the user profile page
Key Result
Intercepting network calls lets us control and verify API responses during tests, ensuring the app correctly integrates with backend services without relying on real servers.