首页 > 解决方案 > 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

标签: cypress

解决方案


“唯一的区别是返回的响应” - 如果你有一个特定的响应模式要匹配,这里有一个有趣的想法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')

推荐阅读