“唯一的区别是返回的响应” - 如果你有一个特定的响应模式要匹配,这里有一个有趣的想法How to match intercept on response
它使用递归来重复cy.wait('@gam'),直到出现正确的响应。
cy.intercept('GET', '**/gampad/ads?*').as('gam')
function waitFor(alias, partialResponse, maxRequests, level = 0) {
if (level === maxRequests) {
throw `${maxRequests} requests exceeded` // fail the test
}
cy.wait(alias).then(interception => {
const isMatch = Cypress._.isMatch(interception.response, partialResponse)
if (!isMatch) {
waitFor(alias, partialResponse, maxRequests, level+1)
}
})
}
waitFor('@gam', { body: { status: 'Completed' } }, 100)
cy.get('@gam.last') // get the last match
waitFor()我想在调用和拦截之间有一个很小的可能性是cy.get('@gam.last')捕获另一个响应。
此版本返回拦截成功
cy.intercept('GET', '**/gampad/ads?*').as('gam')
Cypress.Commands.add('waitFor', (alias, partialResponse, maxRequests, level = 0) => {
if (level === maxRequests) {
throw `${maxRequests} requests exceeded`
}
return cy.wait(alias)
.then(interception => {
const isMatch = Cypress._.isMatch(interception.response, partialResponse)
if (isMatch) {
return interception
} else {
return cy.waitFor(alias, partialResponse, maxRequests, level+1)
}
})
})
cy.waitFor('@gam', { body: { status: 'Completed' } }, 100)
.its('response.body.status')
.should('eq', 'Completed')