← Back to libraryQuestion 176 of 468
🌲CypressIntermediate

cy.intercept — Network Stubbing and Spying

📌 Definition:

cy.intercept lets you spy on, stub, or modify network requests and responses. It makes tests deterministic by controlling what the backend returns and lets you assert that requests were made correctly.

📖 Detailed Explanation:

cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers') stubs a response so the test does not depend on a real server. You can wait for it with cy.wait('@getUsers') and assert on the request/response. Intercept can also just SPY (no stub body) to verify a call happened with the right payload, force error responses (statusCode 500) to test error handling, add delays to test spinners, or dynamically modify responses. This is one of Cypress's biggest advantages over Selenium — full control of the network layer from the test.

🔑 Key Points:
  • Stub, spy, modify, or delay HTTP requests/responses
  • Alias with .as() then cy.wait('@alias') to synchronize and assert
  • Force error/edge responses to test error states deterministically
  • A major Cypress advantage — network control from the test
🌍 Real-World Example:

To test the empty-state UI reliably: cy.intercept('GET', '/api/items', { body: [] }).as('items'); cy.visit('/list'); cy.wait('@items'); cy.get('[data-cy=empty]').should('be.visible'); — no need to arrange an empty database.

🎯 Scenario-Based Interview Question:

Your test for the '500 error' banner is flaky because the real API rarely fails. How do you test it deterministically?