从响应 A (/list.json
) 我的应用程序收到一个项目列表。根据 A 的输出,我的应用程序针对各个项目(/one.txt
、/two.txt
、...)发出另一组请求 B。
现在,在我的测试中,我想确保所有响应 B 返回 HTTP 200。
等待(cy.wait
)响应 A 没问题。然而,等待响应 B 更困难,因为我必须在收到响应 A 后才开始等待,在那里我了解响应 B。
我尝试了两种选择:
这些都不起作用。使用选项 1 我得到
`cy.wait()` timed out waiting `5000ms` for the 1st request to the route: `one.txt`. No request ever occurred
通过选项 2,即使 /two.txt
不存在,我也获得了通过。看起来响应 B 的 cy.wait
是在收到响应后添加的
最佳答案
由于所有请求都是在访问时触发的,并且是动态的,因此您需要一个处理所有请求的拦截。
对我来说,这意味着添加一些 JavaScript 和动态别名。
// avoid status code 304, disable browser cache
Cypress.automation('remote:debugger:protocol', {
command: 'Network.clearBrowserCache'
})
describe('spec', () => {
it('test', () => {
let items = [];
cy.intercept('GET', '*', (req) => {
const slug = req.url.substring(req.url.lastIndexOf('/') + 1)
if (slug === 'list.json') {
req.alias = 'list'
}
if (items.includes(slug)) {
req.alias = 'item'
}
req.continue((res) => {
if (slug === 'list.json')) {
items = res.body;
}
})
})
cy.visit('https://demo-cypress.netlify.app');
cy.wait('@list') // wait for list
.then(() => { // now items is populated
for (let item of items) { // really just need the count
cy.wait('@item').then(interception => { // wait n-times
expect(interception.response.statusCode).to.eq(200);
})
}
})
})
})
关于cypress - 如何让 cypress 等待依赖于另一个响应的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73580430/