0
0
CypressHow-ToBeginner ยท 4 min read

How to Use cy.intercept in Cypress for Network Stubbing and Testing

Use cy.intercept in Cypress to spy on or stub network requests by specifying the HTTP method and URL pattern. It lets you control responses or observe requests during tests, improving test reliability and speed.
๐Ÿ“

Syntax

The basic syntax of cy.intercept includes specifying the HTTP method, the URL or URL pattern to intercept, and optionally a response to stub or a callback to modify the request or response.

  • method: HTTP method like GET, POST, etc.
  • url: URL string or pattern to match requests
  • response: (optional) object or function to stub the response
javascript
cy.intercept(method, url, response?)
๐Ÿ’ป

Example

This example shows how to intercept a GET request to '/api/users' and stub a custom response. It demonstrates controlling the server response to test UI behavior without relying on the real backend.

javascript
describe('User API test', () => {
  it('stubs GET /api/users with custom data', () => {
    cy.intercept('GET', '/api/users', {
      statusCode: 200,
      body: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }],
    }).as('getUsers')

    cy.visit('/users')

    cy.wait('@getUsers').its('response.statusCode').should('eq', 200)

    cy.get('.user-list').should('contain.text', 'Alice').and('contain.text', 'Bob')
  })
})
Output
Test passes if the stubbed users appear on the page and the intercepted request returns status 200.
โš ๏ธ

Common Pitfalls

Common mistakes when using cy.intercept include:

  • Not using .as() to alias the intercept for easier waiting and assertions.
  • Incorrect URL patterns causing the intercept to not match requests.
  • Forgetting to stub the response when needed, leading to flaky tests if the backend is slow or unavailable.
  • Using cy.route (legacy) instead of cy.intercept.
javascript
/* Wrong: No alias and incorrect URL pattern */
cy.intercept('GET', '/api/userz', { body: [] })

/* Right: Correct URL and alias for waiting */
cy.intercept('GET', '/api/users', { body: [] }).as('getUsers')
๐Ÿ“Š

Quick Reference

ParameterDescriptionExample
methodHTTP method to intercept'GET', 'POST', 'PUT', etc.
urlURL or pattern to match requests'/api/users', '**/login'
responseStubbed response or callback{ statusCode: 200, body: {...} } or (req) => {...}
aliasName to reference intercept.as('getUsers')
waitWait for intercepted requestcy.wait('@getUsers')
โœ…

Key Takeaways

Use cy.intercept to spy on or stub network requests by specifying method and URL.
Always alias intercepts with .as() for easier waiting and assertions.
Stub responses to make tests faster and independent of backend availability.
Use URL patterns carefully to ensure intercept matches the intended requests.
Avoid legacy cy.route; prefer cy.intercept for modern Cypress tests.