cypress - cy.intercept 找到多个匹配器。是否可以只等待最后一个网络匹配器?
问题描述
我有一个网络请求要监视,它总是会返回多个匹配器。前几个匹配器通常不包含我需要执行断言的数据,我只需要监视找到的最后一个匹配器。
目前,在到达最后一个匹配器之前,我必须做一个倍数cy.wait()
,这并不理想。只是想知道是否有更好的方法只等待最后一个匹配器?
所有拦截器网络请求都具有相同的“GET”和 url 模式,唯一的区别是返回的响应。
cy.intercept('GET', '**/gampad/ads?*').as('gam'); //this will usually return a few matchers
cy.wait('@gam'). //only want to spy on the last gam request
解决方案
“唯一的区别是返回的响应” - 如果你有一个特定的响应模式要匹配,这里有一个有趣的想法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')
推荐阅读
- c# - 动态对象不包含来自引用的属性定义
- vue.js - 在 webcomponent 构建中使用插槽时,VueJS $children 为空
- node.js - 为什么在 Node.js 中使用猫鼬模式
- python - 按行中的值从熊猫数据透视表中过滤
- machine-learning - 尝试调用函数时 Octave 中的错误:第 1 行第 1 列附近未定义
- node.js - Mongoose 全文搜索未正确过滤
- php - 将域从 DO 帐户 droplet 移动到另一个 DO 帐户 droplet
- .net-core - 在 Blazor 中筛选分页列表
- wpf - 从 ClipboardWatcher 绑定数据
- google-cloud-platform - Google Cloud Platform - Dataflow 不使用 KMS 密钥解密数据