0
0
Cypresstesting~10 mins

cy.intercept() for request interception in Cypress - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses cy.intercept() to intercept a network request and verify that the intercepted response contains the expected data.

Test Code - Cypress
Cypress
describe('API request interception test', () => {
  it('intercepts GET /api/users and checks response', () => {
    cy.intercept('GET', '/api/users', {
      statusCode: 200,
      body: { users: [{ id: 1, name: 'Alice' }] }
    }).as('getUsers');

    cy.visit('/users');

    cy.wait('@getUsers').its('response.statusCode').should('eq', 200);
    cy.get('#user-list').should('contain.text', 'Alice');
  });
});
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1cy.intercept() is set up to intercept GET requests to /api/users and respond with a mocked user listTest runner is ready, intercept is active-PASS
2cy.visit('/users') navigates the browser to the users pageBrowser loads the /users page, triggering the GET /api/users request-PASS
3cy.wait('@getUsers') waits for the intercepted GET /api/users request to completeIntercepted request completes with mocked responseCheck that response status code equals 200PASS
4cy.get('#user-list') finds the user list element and checks it contains text 'Alice'User list element is visible on the page with mocked user dataVerify that user list contains 'Alice'PASS
Failure Scenario
Failing Condition: The intercepted request does not return the mocked response or the page does not render the user list correctly
Execution Trace Quiz - 3 Questions
Test your understanding
What does cy.intercept() do in this test?
AIntercepts the GET /api/users request and returns a mocked response
BClicks a button on the page
CNavigates to the /users page
DChecks the text inside an element
Key Result
Use cy.intercept() to control and test network requests by mocking responses, which helps isolate frontend behavior from backend dependencies.