Understanding Cypress Intercept
On This Page What is Cypress Intercept?May 06, 2026 · 14 min read · Tool Comparison
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. 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: 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. Below are the various reason why the cypress intercept is a great characteristic and why you should use it. Benefits of use the Cypress Intercept: 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 With cypress intercept you can also throttle the speed of the API response and corroborate how the application ’ s execution abilities. In this example, you intercept a exceptional request and slow the reply by 150,000 milliseconds. Read More: You can use Cypress intercept to 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. 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. 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. The cy.intercept lead second argument as the request body that you can direct it when you intercept the request. 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: 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. Below are the ways to intercept net asking in Cypress: 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. 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. You can likewise ensure the API intercepted matches the exact method (GET, POST, PATCH etc ..) Example: You can pass the first parameter with the expected method, and the 2d parameter will be the URL to check thecy.intercept ()method incisively. Along with the method and URL, you can also match the interception URL with the options below Example: Read More: 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 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 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. 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. Setting the alternative {forceNetworkError: true} for the intercept will stop the matching URL reaching the server and mimic the meshing error. 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. 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 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 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: 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. Here are the reasons why you must choose to run Cypress examination on existent devices: 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: Read More: Read More: Understanding Cypress Use Cases Tool Comparisons 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. 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 On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Understanding Cypress Intercept
What is Cypress Intercept?
What is meant by Intercepting Network Requests?
Why should you use Cypress intercept?
Why Use Cypress Intercept for Managing Network Requests?
How to use Cypress Intercepts for Security and Performance Testing?
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)})})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 '')})})Use Cases of Cypress Intercepts
1. Intercept and Wait for petition to complete
it (`` cypress intercept example '', () = & gt; {cy.intercept (`` api/products '') .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')})2. Modify the Request before sending it to the Server
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)})})cy.intercept ({
method: "POST",
"url": `` /api/register ''
},{
username: `` newUserName '', password:'password123 '
}).as(`` registerForm '')3. Mock the response
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 '')})Ways to Intercept Network Requests in Cypress
1. Matching the URL
cy.intercept (`` api/products '') .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')
2. HTTPS Method Matching
cy.intercept (`` GET '', '' api/products '') .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')
3. Matching with RouteMatcher
cy.intercept ({method: `` GET '', url: `` api/products '', headers: {`` accept '': `` application/json, text/plain, * / * ''}}) .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')4. Pattern Matching
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
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)})6. Create a exam for an error case
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)})7. Testing orotund set of information and Default province
it (`` Load data from fixture '', () = & gt; {cy.intercept (`` GET '', `` api/products '', {fixture: `` products ''}) .as (`` productList '') cy.visit (`` https: //www.bstackdemo.com/ '') cy.wait (`` @ productList '')})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
cy.get (`` @ idToken '') .then ((token) = & gt; {cy.intercept (`` /api/ * '', ({headers}) = & gt; {{header ['Authorization '] = ` Bearer $ {token} `}}) cy.visit (`` / '')})9. Stubbing vs. not Stubbing
Overriding an Existing Cypress Intercept
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?
Why use BrowserStack Automate for Cypress Tests?
Utile Resources for Cypress
Conclusion
Frequently Asked Questions
Related Guides
Automate This With SUSA
Test Your App Autonomously