API Mocking In Cypress
- Radek Stolarczyk
- 1 day ago
- 2 min read
API mocking is a powerful Cypress feature that allows tests to run faster, more reliably, and independently of backend data. This page serves as a hands-on reference for how API interception works in Cypress.
Cypress API Interception Overview
Cypress provides the cy.intercept() command to intercept browser API calls and optionally return mock responses.
There are three common ways to define an intercept:
URL + response
Method + URL + response (recommended for clarity)
Router matcher object (advanced and more precise)
Most real-world tests should use the Method + URL approach to avoid accidental matches.
Setting Up API Mocks
API mocks must always be defined before the application triggers the request. This usually means intercepts should be placed at the top of the test, before cy.visit() or user actions.
Basic Example
Why Use Fixtures?
For larger or reusable responses, fixture files are preferred over inline objects.
Benefits:
Cleaner test code
Easier maintenance
Reusable across multiple tests
Fixtures are stored in the cypress/fixtures folder and referenced like this:

Wildcard URL Matching
Wildcards help keep intercepts flexible and resilient.
Base URL Wildcards (**)
Matches any base URL
Avoids repeating full API paths
Useful across environments (local, staging, prod)
Query Parameter Wildcards (*)
Handles dynamic query parameters
Prevents test failures when parameters change
Example: Mocking Multiple Endpoints
In this example:
The real API is never called
The UI renders using fixture data
The test remains fast and deterministic
Modifying API Responses (Response Interception)
Cypress can also intercept a request, let it hit the server, modify the response, and send it back to the application.
This is useful for:
Edge-case testing
Modify only part of the api response
Avoiding database manipulation
Example: Modifying Article Title
The Cypress Runner will display “res modified”, confirming that the response was changed.
Router Matcher (Advanced Configuration)
Router matcher objects allow precise interception control using structured options instead of strings.
Example
Useful Router Matcher Options
pathname – precise path matching
query – match specific query parameters
headers – intercept only requests with certain headers
method arrays – intercept multiple methods
times – intercept only the first request
After the first call, all subsequent requests pass through normally.
Summary
Cypress API mocking enables:
Faster tests
Stable and predictable results
Easier edge-case validation
Reduced dependency on backend data