Master Cypress Intercept with Ease

Discover how to intercept and test network requests effortlessly using Cypress in your automation testing workflow.

Get Started free
Home Guide Understanding Cypress Intercept

Understanding Cypress Intercept

By Gurudatt Ananthapadmanabha, Community Contributor -

Cypress is a popular web automation tool that runs inside a browser and allows the user to automate Web Interactions, UI Elements validation, and API calls. Cypress provides a powerful feature called Intercept, using which you can listen to/fiddle with network requests that happen within the browser.

This guide explains in detail Cypress intercept, its use cases and ways to intercept network requests in Cypress.

What is meant by Intercepting Network Requests?

When a user performs any action in the web application that retrieves data, an API call will be performed to get/update the data. These API calls can be listened and modified based on the requirement, this is called Intercepting.

What is Cypress Intercept?

Cypress 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 using cy.intercept()

Why should you use Cypress intercept?

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

  • Listen and Wait for a particular HTTP request. This will ensure our test 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 response data
  • Listen to a specific HTTP request and cancel that request
  • Listen to a specific HTTP request and slow down the response time
  • Listen to a specific HTTP request and modify its response code to check the error handling

How to use Cypress Intercepts for Security and Performance Testing?

Cypress Intercept can be used for Security testing as it can listen and modify any HTTP request. You can ensure that our application can handle XSS attacks by sending a script in the HTTP request body.

Below is an example of an XSS attack

it("check xss attack", () => {
   cy.intercept({
       method: "POST",
       "url": "/api/register"
   },{
        username: "<script>alert('XSS')</script>", 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) => {
     expect(response.statusCode).to.eq(400)
   })
})

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

it("test network throttle", () => {
  
   cy.intercept("api/products", (req) => {
       req.continue((res) => {
           res.setDelay(15000)
       })
   }).as("productList")
   cy.visit("https://www.bstackdemo.com/")
   cy.wait("@productList").then((responseData) => {
       cy.log(responseData.response.body)
       cy.wrap(responseData.response.body).its("products").its(0)
          .should("have.property", "title", "iPhone 12")
   })
 })

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

Use Cases of Cypress Intercepts

You can use Cypress intercept to

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

1. Intercept and Wait for request to complete

cy.intercept() allows the user to listen to a specific request and wait for the request to complete using aliasing. This will help reduce the flakiness in the test as you are not just waiting for the element to load but also for the API request to complete and retrieve the data.

it("cypress intercept example", () => {
   cy.intercept("api/products").as("productList")
   cy.visit("https://www.bstackdemo.com/")
   cy.wait("@productList")
})

In the above test, you access BrowserStack’s demo website and wait for the API/products request to complete.

Before performing any action that triggers the API request, you must use the intercept command and give an alias name. Once the action is performed, you can then wait for the request to be completed using 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 server. This helps to ensure the backend has better error-handling capability.

it("check xss attack", () => {
   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) => {
     expect(response.statusCode).to.eq(401)
   })
})

The cy.intercept takes second parameter as the request body that you can send it when you intercept the request.

cy.intercept({
       method: "POST",
       "url": "/api/register"
   },{
        username: "newUserName", password: 'password123'
   }).as("registerForm")

Note that in the above code, you are listening to an API request “/api/register” with the POST method. This object is our first parameter to the cy.intercept and the second parameter is the object that you want to send to server when request matching is intercepted.

3. Mock the response

cy.intercept allows the user to mock the response for the intercepted request. This will help to speed up the testing process by simply mocking the response instead of creating the data physically.

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

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

it("mock response", () => {
   cy.intercept("GET", "api/products", {
      statusCode: 200,
      body: {
       "products": [
           {
               "availableSizes": [
                   "Apple"
               ],
               "currencyFormat": "$",
               "currencyId": "USD",
               "description": "iPhone 12",
               "id": 1,
               "installments": 9,
               "isFav": false,
               "price": 799,
               "sku": "iPhone12-device-info.png",
               "title": "iPhone 12"
           },
           {
               "availableSizes": [
                   "Apple"
               ],
               "currencyFormat": "$",
               "currencyId": "USD",
               "description": "iPhone 12 Mini",
               "id": 2,
               "installments": 9,
               "isFav": false,
               "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

1. Matching the URL

You can match the exact URL to intercept using the cy.intercept()

Example:

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 also 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 second parameter will be the URL to match the cy.intercept() method exactly.

3. Matching with RouteMatcher

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

Ways to intercept Network requests in Cypress using Routematcher

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")

4. Pattern Matching

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

Cypress supports using wildcard or Regular expressions to find the matching requests

Example

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

5. Testing your app’s API

You can intercept 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 elements.

Example

cy.intercept({
       method: "GET",
       url: "api/products",
       headers: {
           "accept": "application/json, text/plain, */*"
       }
       }
   ).as("api")
cy.visit("https://www.bstackdemo.com/")
cy.wait("@api").its("response").then((response) => {
       expect(response.statusCode).to.eq(200)
       expect(response.body.products).to.have.length(25)
   })

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

6. Create a test for an error case

With cypress intercept, you can force the intercepted request to fail and validate the application behavior.

The below example will cancel the request reaching from the server.

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

Setting the option {forceNetworkError: true} for the intercept will stop the matching URL reaching the server and mimicking the network error.

7. Testing large set of data and Default state

With Cypress Intercept, you can test the loading of a large set of data in our application without creating it. If you want to test the pagination feature in the application, you will need to create a larger set of data, which will be time-consuming.

You can intercept the API that retrieves the data, and instead of fetching data from the server, you can replace it with our own data coming from a testData.json file placed under the fixture folder in our Cypress project.

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

You don’t need to import any file; all you need to do is create the file under the fixture folder and mention the name of the file as the value for the fixture. Cypress will, by default, look for the file under the fixture folder and import it during run time.

you can also test the default state by not passing any data in the response body and validate the application behavior.

Example

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

8. Handle authorization

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

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

9. Stubbing vs. not Stubbing

When you mock the response of an API, this is called stubbing. The advantage of stubbing is that it speeds up the testing process at an early stage 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 application is ready to handle all sorts of data combinations. You should also write tests that will have real-time data coming from a real API. This will ensure our application is production-ready.

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 pass a different set of data as a response. You can override the intercept with the same alias name, and that will return the overridden response data.

describe.only("check cypress intercept feature", () => {

   beforeEach(() => {
       cy.intercept("GET", "api/products", {
           statusCode: 200,
           body: {
           "products": []
        }
        }).as("productList")
   })

   it("Test default state", () => {
       cy.visit("https://www.bstackdemo.com/")
       cy.wait("@productList")
     })

     it("Test mocked state", () => {
       cy.intercept("GET", "api/products", {
           statusCode: 200,
           body: {
           "products": [{
               "availableSizes": [
                   "Apple"
               ],
               "currencyFormat": "$",
               "currencyId": "USD",
               "description": "iPhone 12",
               "id": 1,
               "installments": 9,
               "isFav": false,
               "price": 799,
               "sku": "iPhone12-device-info.png",
               "title": "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 tests on real devices:

  1. Authentic User Experience: Real devices provide accurate insights into how your application performs in real-world conditions, including varying network types, screen sizes, and operating systems.
  2. Uncover Edge Cases: Simulations on virtual environments might miss device-specific issues like rendering glitches, touch responsiveness, or memory constraints.
  3. Enhanced Accuracy: Network requests can behave differently on real devices due to factors like hardware configurations or mobile-specific browser optimizations.
  4. Reliable Debugging: Testing on real devices ensures that the issues you detect are genuine and replicable, reducing the time spent on false positives.
  5. Comprehensive Test Coverage: With access to a wide range of real devices, you can ensure your Cypress intercept tests cover the full spectrum of user scenarios.

BrowserStack Automate Banner

Why use BrowserStack Automate for Cypress Tests?

BrowserStack is an all-in-one testing platform that offers an extensive range of real devices, operating systems, 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 range of browsers and operating systems without needing local infrastructure. Ensure your application performs consistently across platforms.
  • Parallel Testing: Speed up testing cycles with BrowserStack Automate, enabling simultaneous execution of multiple Cypress test suites. Accelerate feedback loops and deploy faster.
  • CI/CD Integration: Seamlessly integrate with popular CI/CD tools like Jenkins, Travis CI, CircleCI, and GitHub Actions. Automate testing directly within your development pipeline for streamlined workflows.
  • Advanced Debugging Tools: Leverage detailed logs, screenshots, and video recordings of test sessions to quickly identify and resolve issues, ensuring smoother debugging and more efficient testing.
  • Testing on Real Devices: Go beyond simulations—test on real devices in the cloud, from the latest models to legacy hardware, for accurate and real-world results.
  • Customizable Test Execution: Adapt testing to your specific requirements using BrowserStack’s intuitive UI or APIs, giving you complete control over your test runs.

Conclusion

Mastering Cypress intercepts is essential for handling API responses, asynchronous operations, and external functions effectively. By integrating intercepts with Cypress’s native commands, you can create more flexible, reliable, and readable test scripts, significantly enhancing your automation workflow.

For scalable, reliable Cypress testing, BrowserStack Automate offers 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.

Try BrowserStack Now

Tags
Automation Testing Cypress Website Testing

Featured Articles

Cypress vs Selenium vs Playwright vs Puppeteer: Core Differences

Handling Test Failures in Cypress A Comprehensive Guide

Automation Tests on Real Devices & Browsers

Seamlessly Run Automation Tests on 3500+ real Devices & Browsers