Cypress Interception Lifecycle

Profile picture for user arilio666

When an HTTP request is being sent from our app that matches one or more registered intercepted routes lifecycle of cy.intercept() begins here.

Every interception has two phases request and response phase. The cy.intercept() routes are matched in the reverse order except for the routes defined with  { middleware: true }.

  • { middleware: true } always runs first.
  • This causes cy.intercept() to declare by overlapping defined.
Cypress Interception Lifecycle

Request Phase:

1. Request phase begins with the first matching route.
2. Handler was supplied to cy.intercept() else continue to step 7.
3. If the handler was a static response, end the request with that specific response.
4. If the handler was a function, call that function with req. The first argument sees the incoming requests for more info on the req object.
    If req.reply() is called end request phase at once with the response.
    If req.continue() is called end request phase, transfer the request to the destination server.
5. Wait for the promise if the handler returns a promise.
6. Merge modifications to the request object with the actual request.
7. If another matching intercept exists, turn back to step 2 with the route.
8. The response phase begins once the requested outgoing to the destination server is sent and it has ended.

Response Phase:

1. Get list of the before:response registered event listeners.
2. Call each before:response with res object.
  If res.send() is called end response phase, merge arguments with that response.
  Await if any promise is returned.
3. If res.continue() with a callback is declared, call it with the res object.
  If res.send() is called end response phase, merge arguments with that response.
  Await if any promise is returned.
4. Get list of response event listeners.
5. Call with res object for each response listener.
  If res.send() is called end response phase, merge arguments with that response.
  Await if any promise is returned.
6. Send the response to the browser.
7. Get list of after:response event listeners once the response is over.
8. Call with res object for each after:response.
  Await if any promise is returned.
9. End response phase.