You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中检测满足OR条件的多个API请求调用?

解决Cypress中验证多个API请求至少一个被调用的问题

对于Cypress初学者来说,默认断言逻辑是“与(AND)”,要实现“或(OR)”的验证逻辑,需要手动收集两个请求的调用状态并进行判断。以下是两种实用的解决方案:

方案一:使用cy.all并行检查请求状态

这是最直接的方法,适合单次使用场景:

步骤1:拦截目标请求并设置别名

先确保你已经用cy.intercept拦截了需要验证的两个请求,并给它们设置别名:

// 替换为你的实际请求方法和URL
cy.intercept('GET', '/api/request-1').as('request1')
cy.intercept('POST', '/api/request-2').as('request2')

步骤2:触发操作并验证“或”逻辑

点击按钮后,通过cy.all并行获取两个请求的调用状态,再判断至少一个为true:

// 触发按钮点击操作
cy.get('button').click()

// 并行获取两个请求的调用状态
cy.all(
  cy.get('@request1').then(interception => interception.called),
  cy.get('@request2').then(interception => interception.called)
).then(([isRequest1Called, isRequest2Called]) => {
  // 核心断言:至少一个请求被调用
  expect(isRequest1Called || isRequest2Called).to.be.true

  // 可选:根据调用情况打印日志
  if (isRequest1Called) {
    cy.log(`Request was made to 'REQUEST1_URL'`)
  }
  if (isRequest2Called) {
    cy.log(`Request was made to 'REQUEST2_URL'`)
  }
})

补充说明

  • interception.called是Cypress拦截对象的内置属性,返回布尔值,表示该请求是否被触发过。
  • 如果请求存在延迟,可以给cy.get添加超时参数,比如cy.get('@request1', { timeout: 10000 }),延长等待时间。

方案二:封装自定义断言(适合复用场景)

如果需要在多个测试用例中复用“至少一个请求被调用”的逻辑,可以封装自定义命令:

// 在cypress/support/commands.js中添加自定义命令
Cypress.Commands.add('assertAtLeastOneRequestCalled', (aliases) => {
  return cy.all(
    ...aliases.map(alias => cy.get(alias).then(interception => interception.called))
  ).then(calledStatuses => {
    const atLeastOneCalled = calledStatuses.some(status => status)
    expect(atLeastOneCalled).to.be.true
    
    // 打印被调用的请求日志
    calledStatuses.forEach((status, index) => {
      if (status) {
        cy.log(`Request was made to '${aliases[index].replace('@', '')}_URL'`)
      }
    })
  })
})

// 在测试用例中直接调用
cy.get('button').click()
cy.assertAtLeastOneRequestCalled(['@request1', '@request2'])

内容的提问来源于stack exchange,提问作者ElVincitore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:06:28