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

Cypress如何测试出现顺序不固定的两个modal弹窗的展示效果

问题原因

你当前的代码强制按A先出现、B后出现的顺序匹配,若B先弹出,第一行代码匹配不到A的内容就会直接超时失败。

解决方案

根据你的弹窗交互逻辑选对应写法即可:

方案1:弹窗会同时/先后保留在DOM中(仅显示隐藏切换)

直接断言目标弹窗元素同时包含两个文本即可,Cypress会自动重试直到条件满足或超时:

cy.get("[data-cy='dialog-confirm-content']", {timeout: 20000})
  .should($el => {
    expect($el.text()).to.include(data.notifA)
    expect($el.text()).to.include(data.notifB)
  })

方案2:弹窗每次仅展示一个,关闭后才会出现下一个

用循环匹配任意顺序的弹窗,匹配到一个后移除待匹配列表,直到全部匹配完成:

const toBeMatched = [data.notifA, data.notifB]
// 循环两次匹配两个弹窗
Cypress._.times(2, () => {
  cy.get("[data-cy='dialog-confirm-content']").then($el => {
    const currentText = $el.text()
    // 校验当前弹窗是待匹配的内容之一
    const matched = toBeMatched.find(item => currentText.includes(item))
    expect(matched, `当前弹窗内容匹配预期`).to.exist
    // 移除已匹配的内容
    toBeMatched.splice(toBeMatched.indexOf(matched), 1)
  })
  // 这里补充你的弹窗关闭逻辑,比如点击确认按钮:
  // cy.get("[data-cy='dialog-confirm-button']").click()
})

方案3:不需要操作弹窗,仅校验两个弹窗都出现过

用Cypress.Promise.all并行执行两个匹配逻辑,不限制顺序:

Cypress.Promise.all([
  cy.contains("[data-cy='dialog-confirm-content']", data.notifA, {timeout: 20000}),
  cy.contains("[data-cy='dialog-confirm-content']", data.notifB, {timeout: 20000})
])

内容的提问来源于stack exchange,提问作者Oliv' G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:36:04