0
0
CypressHow-ToBeginner ยท 4 min read

How to Use cy.intercept for Mocking in Cypress Tests

Use cy.intercept in Cypress to stub or mock network requests by specifying the HTTP method and URL, then providing a mocked response. This lets you control API data during tests without hitting the real server.
๐Ÿ“

Syntax

The basic syntax of cy.intercept includes the HTTP method, the URL to intercept, and the mocked response or handler function.

  • method: HTTP method like 'GET', 'POST', etc.
  • url: The URL or pattern to match requests.
  • response: The mocked data or function to send back.
javascript
cy.intercept(method, url, response)
๐Ÿ’ป

Example

This example shows how to mock a GET request to '/api/users' and return a fixed list of users. The test visits a page and verifies the mocked data is displayed.

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

    cy.visit('/users')

    cy.wait('@getUsers')

    cy.get('[data-cy=user-name]').should('have.length', 2)
    cy.get('[data-cy=user-name]').first().should('contain.text', 'Alice')
  })
})
Output
Test passes if the page shows 2 user names: Alice and Bob, confirming the mock worked.
โš ๏ธ

Common Pitfalls

Common mistakes when using cy.intercept include:

  • Not using the correct URL or method, so the intercept never matches.
  • Forgetting to wait for the intercepted request with cy.wait(), causing flaky tests.
  • Mocking responses without proper status codes or structure, leading to unexpected app behavior.

Always verify your intercept matches the actual request and use aliases to wait for them.

javascript
/* Wrong: URL mismatch, intercept won't trigger */
cy.intercept('GET', '/api/userz', { body: [] })

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

Quick Reference

ParameterDescriptionExample
methodHTTP method to intercept'GET', 'POST', 'PUT'
urlURL or pattern to match requests'/api/users', '**/login'
responseMocked response data or function{ statusCode: 200, body: {...} }
aliasName to reference the intercept.as('getUsers')
cy.wait()Wait for the intercepted requestcy.wait('@getUsers')
โœ…

Key Takeaways

Use cy.intercept(method, url, response) to mock network requests in Cypress.
Always assign an alias with .as() and wait for the request with cy.wait() to ensure test stability.
Match the exact HTTP method and URL pattern to successfully intercept requests.
Mock responses should include realistic status codes and data structure to avoid test errors.
cy.intercept helps isolate frontend tests from backend dependencies by controlling API responses.