Eden Chan
Eden Chan

Reputation: 121

Is there a way to intercept the response of a HTTP request made from the client side in Cypress?

Suppose I have a button that calls a function making a HTTP request, that responds with a the value of a token. After using Cypress to click this button, how can I intercept the response of the HTTP request being made from clicking the button to extract this token?

I have looked into the official Cypress documentation on the intercept method, as well as this article: https://egghead.io/blog/intercepting-network-requests-in-cypress but from what I understand, Cypress is intercepting a HTTP request called directly from the test file, and not the function being called after clicking the client-side button.

It would be much appreciated if one of you knowledgable folks can clarify how to use the intercept method.

Upvotes: 0

Views: 1494

Answers (1)

Fody
Fody

Reputation: 32148

You have it backwards - Cypress intercepts requests from the app, but it cannot intercept requests from the test.

When your test clicks the button, it fires a click event in the app, which then sends the request out and this can be intercepted.

Here's a simple example

it('intercepts request from app', () => {

  cy.intercept('**/guides/guides/network-requests').as('link-intercepted')

  cy.visit('https://docs.cypress.io/api/commands/intercept')

  cy.contains('a', 'Network Requests').click()  // fire event
                                                // which triggers request from app

  cy.wait('@link-intercepted')
  cy.contains('h1', 'Network Requests')  // heading of the new page
})

But a request from the test fails

it('cannot catch requests from test', () => {

  cy.intercept('**/guides/guides/network-requests').as('link-intercepted')
  cy.visit('https://docs.cypress.io/api/commands/intercept')

  // fire request from the test
  cy.request('https://docs.cypress.io/guides/guides/network-requests')

  cy.wait('@link-intercepted')  // waits 5 seconds and fails

})

Upvotes: 2

Related Questions