Understanding Cypress Intercept

On This Page What is Cypress Intercept?May 06, 2026 · 14 min read · Tool Comparison

Understanding Cypress Intercept

Cypressis a modern, open-source test mechanisation fabric known for its flexibility and powerful debugging capabilities.

One of its key features is the power to intercept network requests, allowing exploiter to modify, stub, or manipulate reaction in real time. This is particularly useful for testing scenario before backend integration, debug network issues, and simulating different reaction weather.

This guide exploresCypress Intercept, its use example, and how to intercept network requests in Cypress effectively.

What is Cypress Intercept?

intercept allows to listen/Modify the HTTP requests occurring within the browser. This is helpful to speed up the testing process during the development phase itself, as it can mimic the data of an API that is not ready yet. You can intercept such requests that are not ready and mock the response usingcy.intercept ()

Read More:

What is meant by Intercepting Network Requests?

When a user performs any activity in the web covering that recover datum, an API outcry will be performed to get/update the data. These API calls can be listened and modified based on the requirement, this is called Intercepting.

Why should you use Cypress intercept?

Below are the various reason why the cypress intercept is a great characteristic and why you should use it.

  • Listen and Wait for a particular HTTP request. This will ensure our tryout is stable and less flaky if the HTTP requests take more time to load the data.
  • Listen to a specific HTTP request and modify its answer information
  • Listen to a specific HTTP asking and cancel that request
  • Listen to a specific HTTP request and slow down the response clip
  • Listen to a specific HTTP request and qualify its response code to check the error treatment

Why Use Cypress Intercept for Managing Network Requests?

Benefits of use the Cypress Intercept:

  • Testing Real-world Scenarios: It allows us to test many real user scenarios with model, such as server downwards, getting erroneousness messages, slow response, etc.
  • Validate the Network Requests: It help corroborate the various network petition and validate the interface and functionality.
  • Simulate the Response: You can mock the response without even the presence of backed service, which allows us to try the application early.
  • Modify meshwork responses: Network reply can be modified to validate the behaviour on user interfaces.
  • Faster execution: The actual API call, particularly when the information is big, may direct more time. With Cypress intercept and mocking, those calls can be quicker, and the test continuance will be substantially less.

How to use Cypress Intercepts for Security and Performance Testing?

Cypress Intercept can be apply for Security screen as it can listen and modify any HTTP petition. You can ensure that our application can handle XSS attacks by sending a playscript in the HTTP asking body.

Below is an example of an XSS attack

it (`` check xss attack '', () = & gt; {cy.intercept ({method: `` POST '', `` url '': `` /api/register ''}, {username: `` & lt; script & gt; alert ('XSS ') & lt; /script & gt; '', password: 'password123'}) .as (`` registerForm '') cy.get (`` # username '') .type (`` myName '') cy.get (`` # password '') .type (`` password '') cy.get (`` # submit '') .click () cy.wait (`` @ registerForm '') .its (`` answer '') .then ((response) = & gt; {expect (response.statusCode) .to.eq (400)})})

With cypress intercept you can also throttle the speed of the API response and corroborate how the application ’ s execution abilities.

it (`` trial network gun '', () = & gt; {cy.intercept (`` api/products '', (req) = & gt; {req.continue ((res) = & gt; {res.setDelay (15000)})}) .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '') .then ((responseData) = & gt; {cy.log (responseData.response.body) cy.wrap (responseData.response.body) .its (`` products '') .its (0) .should (`` have.property '', `` rubric '', `` iPhone 12 '')})})

In this example, you intercept a exceptional request and slow the reply by 150,000 milliseconds.

Read More:

Use Cases of Cypress Intercepts

You can use Cypress intercept to

  • Wait for a particular request/response to complete habituate aliasing
  • Modify the request before mail it to the server
  • Mock the response

1. Intercept and Wait for petition to complete

cy.intercept () allows the user to listen to a specific asking and wait for the request to dispatch using aliasing. This will assist trim the flakiness in the trial as you are not just waiting for the constituent to payload but also for the API request to finish and retrieve the datum.

it (`` cypress intercept example '', () = & gt; {cy.intercept (`` api/products '') .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')})

In the above test, you accessBrowserStack ’ s demo websiteand wait for theAPI/productsrequest to complete.

Before performing any action that triggers the API request, you must use the intercept dictation and yield an alias gens. Once the action is performed, you can then look for the asking to be completed employ the alias name.

2. Modify the Request before sending it to the Server

cy.intercept () allows the user to listen to a specific request and then modify its request data before sending it to the host. This helps to ensure the backend has better error-handling capability.

it (`` check xss fire '', () = & gt; {cy.intercept ({method: `` POST '', `` url '': `` /api/register ''}, {username: `` newUserName '', password: 'password123'}) .as (`` registerForm '') cy.get (`` # username '') .type (`` myName '') cy.get (`` # password '') .type (`` password '') cy.get (`` # submit '') .click () cy.wait (`` @ registerForm '') .its (`` response '') .then ((response) = & gt; {wait (response.statusCode) .to.eq (401)})})

The cy.intercept lead second argument as the request body that you can direct it when you intercept the request.

cy.intercept ({

       method: "POST",

       "url": `` /api/register ''

   },{

        username: `` newUserName '', password:'password123 '

   }).as(`` registerForm '')

Note that in the above codification, you are hear to an API asking “ /api/register” with thePOSTmethod. This object is our maiden parameter to thecy.interceptand the second parameter is the object that you want to send to server when request matching is wiretap.

Read More:

3. Mock the response

cy.interceptallows the user to mock the response for the intercepted request. This will help to speed up the screen process by merely mocking the response instead of creating the datum physically.

This will also help to test when the API termination is not ready to send the answer but users can mock and try the front end.

Below is an example that shows how to mock the answer.

it (`` mock response '', () = & gt; {cy.intercept (`` GET '', `` api/products '', {statusCode: 200, body: {`` products '': [{`` availableSizes '': [`` Apple ''], `` currencyFormat '': `` $ '', `` currencyId '': `` USD '', `` description '': `` iPhone 12 '', `` id '': 1, `` installments '': 9, `` isFav '': false, `` terms '': 799, `` sku '': `` iPhone12-device-info.png '', `` title '': `` iPhone 12 ''}, {`` availableSizes '': [`` Apple ''], `` currencyFormat '': `` $ '', `` currencyId '': `` USD '', `` description '': `` iPhone 12 Mini '', `` id '': 2, `` installments '': 9, `` isFav '': mistaken, `` price '': 699, `` sku '': `` iPhone12-device-info.png '', `` title '': `` iPhone 12 Mini ''},]}}) .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')})

Talk to an Expert

Ways to Intercept Network Requests in Cypress

Below are the ways to intercept net asking in Cypress:

1. Matching the URL

You can jibe the precise URL to wiretap expend the cy.intercept ()

Example:

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

cy.intercept (`` api/products '') .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')

You need to pass “API/products” as the URL to the intercept method. This will ensure that Cypress intercepts only the URL that exactly matches the passed URL.

2. HTTPS Method Matching

You can likewise ensure the API intercepted matches the exact method (GET, POST, PATCH etc ..)

Example:

cy.intercept (`` GET '', '' api/products '') .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')

You can pass the first parameter with the expected method, and the 2d parameter will be the URL to check thecy.intercept ()method incisively.

3. Matching with RouteMatcher

Along with the method and URL, you can also match the interception URL with the options below

Example:

cy.intercept ({method: `` GET '', url: `` api/products '', headers: {`` accept '': `` application/json, text/plain, * / * ''}}) .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')

Read More:

4. Pattern Matching

You can use patterns in the URL to tap the request in Cypress.

Cypress supports expend wildcard or Regular expressions to happen the matching petition

Example

cy.intercept ({method: `` GET '', url: `` api/ * '', cope: {`` accept '': `` application/json, text/plain, * / * ''}}) .as (`` api '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ api '')

5. Testing your app ’ s API

You can tap and validate the response of the intercepted URL. This is helpful to ensure the data retrieved from the URL is proper and you are not just validating the UI constituent.

Example

cy.intercept ({method: `` GET '', url: `` api/products '', headers: {`` consent '': `` application/json, text/plain, * / * ''}}) .as (`` api '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ api '') .its (`` response '') .then ((reaction) = & gt; {expect (response.statusCode) .to.eq (200) anticipate (response.body.products) .to.have.length (25)})

In this example, you wait for the intercepted asking to complete, and then you verify the status code and the response body to ensure they have the expected length of array target.

6. Create a exam for an error case

With cypress intercept, you can pressure the intercepted request to miscarry and validate the covering doings.

The below instance will scrub the request reaching from the host.

cy.intercept ({method: `` GET '', url: `` api/products '', head: {`` accept '': `` application/json, text/plain, * / * ''}}, {forceNetworkError: true}) .as (`` api '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ api '') .its (`` response '') .then ((response) = & gt; {expect (response.statusCode) .to.eq (200) await (response.body.products) .to.have.length (25)})

Setting the alternative {forceNetworkError: true} for the intercept will stop the matching URL reaching the server and mimic the meshing error.

7. Testing orotund set of information and Default province

With Cypress Intercept, you can test the burden of a large set of datum in our application without create it. If you want to test the folio characteristic in the application, you will need to make a larger set of information, which will be time-consuming.

You can intercept the API that find the data, and instead of fetching datum from the server, you can supplant it with our own data come from a testData.json file order under the fixture folder in our Cypress task.

it (`` Load data from fixture '', () = & gt; {cy.intercept (`` GET '', `` api/products '', {fixture: `` products ''}) .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')})

You don & # 8217; t need to spell any file; all you need to do is create the file under the secureness folder and mention the gens of the file as the value for the secureness. Cypress will, by nonpayment, look for the file under the regular folder and importee it during run time.

you can too test the default province by not passing any data in the response body and formalise the covering demeanour.

Example

it.only (`` Test default state '', () = & gt; {cy.intercept (`` GET '', `` api/products '', {statusCode: 200, body: {`` product '': []}}) .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')})

8. Handle potency

To speed up testing, you can log in once and then reuse the nominal across all the API requests. This will save the time taken for repetitive login. You can log in and wrap the authorization item as an alias and then retrieve that, which so can be passed for all the API headers using cy.intercept like in the below example

cy.get (`` @ idToken '') .then ((token) = & gt; {cy.intercept (`` /api/ * '', ({headers}) = & gt; {{header ['Authorization '] = ` Bearer $ {token} `}}) cy.visit (`` / '')})

9. Stubbing vs. not Stubbing

When you bemock the reaction of an API, this is call stub. The reward of stubbing is that it speeds up the examination process at an other degree of development. But ensure that you are testing the real APIs, too, as that will be the actual end-to-end testing.

Stubbing is only to ensure the coating is ready to handle all sorts of information combinations. You should besides write tests that will have real-time datum coming from a real API. This will ensure our application is production-ready.

Read More:

Overriding an Existing Cypress Intercept

You can override the previously defined intercept. This is helpful when changing the mock response only for a few specific tests.

The example below shows how to override the intercept. You have an intercept defined in the BeforeEach with an alias called “productList, ” but in the second test, you have to override that and legislate a different set of information as a response. You can override the intercept with the same alias gens, and that will return the overridden response information.

describe.only (`` check cypress intercept feature '', () = & gt; {beforeEach (() = & gt; {cy.intercept (`` GET '', `` api/products '', {statusCode: 200, body: {`` merchandise '': []}}) .as (`` productList '')}) it (`` Test default state '', () = & gt; {cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')}) it (`` Test mock state '', () = & gt; {cy.intercept (`` GET '', `` api/products '', {statusCode: 200, body: {`` products '': [{`` availableSizes '': [`` Apple ''], `` currencyFormat '': `` $ '', `` currencyId '': `` USD '', `` description '': `` iPhone 12 '', `` id '': 1, `` installment '': 9, `` isFav '': mistaken, `` damage '': 799, `` sku '': `` iPhone12-device-info.png '', `` rubric '': `` iPhone 12 ''}]}}) .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')})})

Why Choose Real Devices for Cypress Intercept Testing?

Here are the reasons why you must choose to run Cypress examination on existent devices:

  1. Authentic User Experience: Real device provide exact insights into how your application performs in real-world weather, including varying net character, blind sizes, and operating systems.
  2. Uncover Edge Cases: Simulations on virtual surround might miss device-specific issues like interpret glitches, touch reactivity, or memory constraint.
  3. Enhanced Accuracy: Network requests can behave differently on existent devices due to factors like hardware configurations or mobile-specific browser optimisation.
  4. Reliable Debugging: Testing on real devices ensures that the issues you detect are genuine and replicable, reducing the time pass on mistaken positive.
  5. Comprehensive: With accession to a wide range of real device, you can ascertain your Cypress intercept tests extend the full spectrum of user scenarios.

Why use BrowserStack Automate for Cypress Tests?

BrowserStack is an all-in-one testing program that offers an extensive compass of existent devices, operating system, and browsers for testing. Here are some of the reasons why you must prefer BrowserStack to run your Cypress tests:

  • Diverse Environment Testing: Execute Cypress tests across a wide scope of browsers and control systems without needing local base. Ensure your application performs consistently across platforms.

Read More:

  • : Speed up testing cycles with BrowserStack Automate, enabling simultaneous performance of multiple Cypress exam suites. Accelerate feedback loops and deploy faster.

Read More:

  • Integration: Seamlessly integrate with democratic CI/CD tools like Jenkins, Travis CI, CircleCI, and GitHub Actions. Automate testing forthwith within your development pipeline for streamlined workflows.
  • Advanced Debugging Tools: Leverage detail logs, screenshots, and video recordings of test sessions to quickly name and decide issue, ensuring sander debugging and more effective examination.
  • Testing on Real Devices: Go beyond simulations—test on real devices in the cloud, from the latest model to bequest hardware, for accurate and real-world results.
  • Customizable Test Execution: Adapt testing to your specific requirements using BrowserStack ’ s nonrational UI or APIs, give you complete control over your test runs.

Utile Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Conclusion

Mastering Cypress intercepts is essential for handling API responses, asynchronous operation, and external functions effectively. By integrating intercepts with Cypress & # 8217; s native bidding, you can create more flexible, reliable, and readable test scripts, importantly heighten your automation workflow.

For scalable, authentic Cypress testing, offer the perfect solution. With a cloud-based infrastructure, real-device support, parallel execution, and seamless CI/CD integrations, it empowers you to run efficient, high-quality tests.

Frequently Asked Questions

1. What is the role of intercept in Cypress?

cy.intercept () bid permit stub, spying, modifying requests, and validating response to ensure the app behaves aright under various use case. It also helps debug and copy edge causa scenario.

2. What is the difference between cy.intercept () and cy.request ()?

cy.intercept () is apply to spy on, stub, or modify network requests the application do. cy.request () is used to make HTTP postulation to an endpoint within the test instantly

Tags
16,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free