1

I want to wait only until a request is sent. I don't want to wait until the request receives a response.

As of now cy.intercept() and cy.wait() wait until the request receives a response. Is there any way to wait just until the request is sent?

For example

cy.intercept(url).as('alias')  
                                      
cy.get('button').click()

cy.wait('@alias')   // only catches when the response returns 
Thelonious
  • 146
  • 10
  • What's the use case here? Is there an animation on the screen you want to test? Some state in between request and response you want to validate? Or is the response just not important to whatever you're testing? – agoff Mar 03 '23 at 14:49
  • The response is not needed, but the request needs to be sent. and also it takes over a minute to get the response, which makes my test case a longer one – Yogendiran Barath Mar 03 '23 at 17:04
  • Would just mocking the entire request work? – agoff Mar 03 '23 at 19:10
  • @YogendiranBarath I have similar case in one of the automation tests. I have to wait approx 12 second to get a proper response from a third party system. We use http `polling ` concept to acheive it and it working well – soccerway Mar 03 '23 at 22:56
  • 1
    Polling would only be needed if the server is flaky and you need to retry the request, according to Cypress documentation. – Thelonious Mar 05 '23 at 23:12

1 Answers1

2

The easiest way is to send a mock response, which by-passes waiting for the server. It's feasible if the app does not use the response.

cy.intercept(url, {}).as('my-alias')  // 2nd argument is a very simple mock response 
                                      // request never gets to the server
// trigger request in app 

cy.wait('@my-alias')                  // should fire on outbound request

If you find the app does complain about the mock response, a stub function could be used instead.

You cannot cy.wait('@stub') on a stub alias, but you can use cy.get('@stub').should('be.called') to do the same thing.

Here's a working example.

const stub = cy.stub().as('stub')     // set up the stub

cy.intercept('**/my/api/items?1', (req) => {

  stub()         // call the stub as soon as the request is made 

  req.reply({
    delay: 60_000, // simulate response after 1 minute
  })
})
.as('response')    // this is the response alias

cy.window().then(win => {
  setTimeout(() => {
    win.fetch('my/api/items?1')       // fire the request after 2 seconds
  }, 2_000)
})

cy.get('@stub').should('be.called')   // wait for stub call up to 4 seconds
                                      // or add a timeout if required

// cy.wait('@response')       // response alias fails after 30 seconds

In your test you can use a shorter version, since you don't need to artificially delay the response

cy.intercept(url, cy.stub().as('stub'))  

// trigger request

cy.get('@stub').should('be.called')
user16695029
  • 3,365
  • 5
  • 21