Cypress: Intercept a route that doesn't exist

Viewed 703

I am currently intercepting the authorization.oauth2 request successfully, but what I would like to do then is to make a request to my localhost (A non-existing route in the application). However, when I do this, I get a 404 error.

Is there anyway to intercept a request to a route that doesn't exist?

  cy.intercept('*authorization.oauth2*', req => {
    cy.request('POST', '/auth/intercept/handle');
    req.reply('');
  });

  // This route doesn't exist:
  cy.intercept('POST', '/auth/intercept/handle', req => {
    // Handle stuff
  });

This is the output of the request:

cy.request() failed on:

https://localhost:4200/auth/intercept/handle

The response we received from your web server was:

  > 404: Not Found

This was considered a failure because the status code was not 2xx or 3xx.

If you do not want status codes to cause failures pass the option: failOnStatusCode: false

-----------------------------------------------------------

The request we sent was:

Method: POST
URL: https://localhost:4200/auth/intercept/handle
Headers: {
  "Connection": "keep-alive",
  "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Cypress/8.1.0 Chrome/89.0.4328.0 Electron/12.0.0-beta.14 Safari/537.36",
  "accept": "/",
  "accept-encoding": "gzip, deflate",
  "content-length": 0
}

-----------------------------------------------------------

The response we got was:

Status: 404 - Not Found
Headers: {
  "x-powered-by": "Express",
  "access-control-allow-origin": "*",
  "content-security-policy": "default-src 'none'",
  "x-content-type-options": "nosniff",
  "content-type": "text/html; charset=utf-8",
  "content-length": "161",
  "date": "Tue, 03 Aug 2021 19:57:39 GMT",
  "connection": "keep-alive"
}
Body: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /auth/intercept/handle</pre>
</body>
</html>

Because this error occurred during a after each hook we are skipping the remaining tests in the current suite: Roles Page
1 Answers

instead of doing a cy.intercept to make a post request from the cy intercept, try using cy.intercept to respond directly to your frontend with the data you want to include. After all, the purpose of cy.intercept is to intercept requests to change data on the request and induce behaviors that we want to test in our frontend.

Try something like this:

const res = { message: true }

cy.intercept(
    {
        method: 'POST',
        url: '*authorization.oauth2*'
    },
    res
)
Related