赛普拉斯:拦截一条不存在的路线
Posted
技术标签:
【中文标题】赛普拉斯:拦截一条不存在的路线【英文标题】:Cypress: Intercept a route that doesn't exist 【发布时间】:2021-10-09 00:34:34 【问题描述】:我目前正在成功拦截authorization.oauth2
请求,但我想做的是向我的本地主机发出请求(应用程序中不存在的路由)。但是,当我这样做时,我会收到 404 错误。
有没有办法拦截到一个不存在的路由的请求?
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
);
这是请求的输出:
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
【问题讨论】:
问题似乎出在示例第 2 行的请求上,而不是拦截。当您请求一个不存在的端点时,404 响应是预期的行为。你希望发生什么? 我希望拦截器捕获请求并运行回调。 我在文档中找到了这个:cy.intercept() cannot be debugged using cy.request()! Cypress only intercepts requests made by your front-end application.
【参考方案1】:
不要使用 cy.intercept 来从 cy 拦截器发出 post 请求,而是尝试使用 cy.intercept 直接向前端响应您想要包含的数据。 毕竟,cy.intercept 的目的是拦截请求以更改请求中的数据并诱导我们想要在前端测试的行为。
试试这样的:
const res = message: true
cy.intercept(
method: 'POST',
url: '*authorization.oauth2*'
,
res
)
【讨论】:
以上是关于赛普拉斯:拦截一条不存在的路线的主要内容,如果未能解决你的问题,请参考以下文章