Cypress Intercept: Matching URL and Method

Profile picture for user arilio666

Intercept is known as obstructing someone or something, but in this case, intercept is used to jam, stub, or spy responses from the route and get answers and compare them.

Intercept is used to spy on API requests and check the response and take the ID from the response to check the response in this order. Intercepts are cleared after every test.

In this article, we will try to match and handle URLs using the intercept command in cypress.

  cy.intercept('/collect?').as('getUrl')
          cy.visit('http://www.programsbuzz.com/')
          cy.window().then((win) => {
            const xhr = new win.XMLHttpRequest()
            xhr.open('GET', '/collect?')
            xhr.send()
          })
          cy.wait('@getUrl')
    

We can see that the intercept command now matches requests of any sort containing the URL '/collect?'.

So this is one way of matching URLs using intercept.

Now our URL has matched a request. We can use this if it has multiple URLs of different requests and wants to match a particular URL based on request.

cy.intercept('POST', '/collect?').as('getUrl')

We can also match using regex.

cy.intercept('POST', '/collect?/*').as('getUrl')

With intercept, advanced URL matching can be done.

cy.intercept({
 https: true
 method: 'POST',
 query: {
   limit: 5
 },
 path: '/collect?'
})

Using this will fetch /collect? URL match with POST request limiting to 5 matched URLs with HTTP header.

Conclusion:

Creatively we can use intercept to match URLs and fetch our required match.