在我的应用程序中,我有一个流程触发两个 POST 请求到相同的端点,但请求正文略有变化。我们如何使用 cypress 来实现这一目标?
请求1:
请求网址:http://localhost:8000/weather/F20210908060000/spot
请求方式:POST
请求正文:
{
"locations": [
{
"timestamp": "2021-09-18T06:00:00.000Z",
"coordinates": [
106.41364531249987,
-15.435157996299878
]
},
{
"timestamp": "2021-09-18T07:00:00.000Z",
"coordinates": [
106.41364531249987,
-15.435157996299878
]
}
],
"elements": [
2
]
}
Run Code Online (Sandbox Code Playgroud)
请求2: 请求URL:
http://localhost:8000/weather/F20210908060000/spot
Run Code Online (Sandbox Code Playgroud)
请求方式:POST
请求正文:
{
"locations": [
{
"timestamp": "2021-09-18T04:00:00.000Z",
"coordinates": [
106.41364531249987,
-15.435157996299878
]
},
{
"timestamp": "2021-09-18T05:00:00.000Z",
"coordinates": [
106.41364531249987,
-15.435157996299878
]
},
{
"timestamp": "2021-09-18T06:00:00.000Z",
"coordinates": [
106.41364531249987,
-15.435157996299878
]
},
{
"timestamp": "2021-09-18T07:00:00.000Z",
"coordinates": [
106.41364531249987,
-15.435157996299878
]
}
],
"elements": [
2
]
}
Run Code Online (Sandbox Code Playgroud)
注意:请求 2 的请求中包含更多数据。
到目前为止我的代码:
cy.intercept("POST", "**/spot", (req) => {
expect(req.locations).to.have.length.above(3);
}).as('postSPOT1');
Weather.activateSPOTWeather()
});
cy.wait('@postSPOT1').its('response.statusCode').should("eq", 200);
Run Code Online (Sandbox Code Playgroud)
这里有一个检查响应的模式如何匹配响应拦截
我将匹配器更改为函数,因为您想要评估与响应部分不匹配的表达式。
cy.intercept("POST", "**/spot").as('postSPOT1')
function waitFor(alias, checkFn, maxRequests, level = 0) {
if (level === maxRequests) {
throw `${maxRequests} requests exceeded`
}
cy.wait(alias).then(interception => {
if (!checkFn(interception)) {
waitFor(alias, checkFn, maxRequests, level+1)
}
})
}
const maxRequests = 10
const checkFn = (interception) => interception.request.locations > 3
waitFor('@postSPOT1', checkFn, maxRequests)
cy.get('@postSPOT1.last')
.then(lastInterception => {
...
})
Run Code Online (Sandbox Code Playgroud)
或者使用cypress-recurse插件
cy.intercept("POST", "**/spot").as('postSPOT1')
recurse(
() => cy.wait('@postSPOT1'),
(interception) => interception.request.locations > 3,
{
log: true,
limit: 10, // max number of iterations
timeout: 30000, // time limit in ms
},
)
cy.get('@postSPOT1.last')
.then(lastInterception => {
...
})
Run Code Online (Sandbox Code Playgroud)
如果正好有两个请求并且您只想要第二个请求,那么等待两次可能会更简单
cy.intercept("POST", "**/spot").as('postSPOT1')
cy.wait('@postSPOT1') // discard
cy.wait('@postSPOT1')
.then(lastInterception => {
...
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5045 次 |
| 最近记录: |