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

Cypress处理多个确认弹窗时事件监听冲突问题求助

解决Cypress中多个确认弹窗监听冲突的问题

问题根源在于cy.on注册的是全局持久化事件监听器,只要不手动移除,它会一直生效。第一个弹窗的监听器没被清除,导致第二个弹窗触发时,两个监听器同时执行,第一个监听器的断言会匹配第二个弹窗的文本,自然失败。

下面是两种可行的解决办法:

方法一:手动移除第一个监听器

处理完第一个弹窗后,用cy.off清除之前的window:confirm监听器,再注册第二个:

// 处理第一个弹窗
cy.on("window:confirm", str => {
  expect(str).to.equal(
    "Please confirm you would like to leave this space. You will no longer be a member of this space."
  );
  return true;
});
// 触发第一个弹窗的操作(比如点击对应按钮)
cy.get("#leave-space-btn").click();

// 移除第一个监听器
cy.off("window:confirm");

// 处理第二个弹窗
cy.on("window:confirm", str => {
  expect(str).to.equal(
    "This will archive the space and any content posted within it. Are you sure you wish to continue?"
  );
  return true; // 别忘了返回true模拟点击确认
});
// 触发第二个弹窗的操作
cy.get("#archive-space-btn").click();

方法二:使用单次监听器cy.once

cy.once只会监听一次事件,触发后自动失效,无需手动移除,更简洁:

// 第一个弹窗用once,仅触发一次
cy.once("window:confirm", str => {
  expect(str).to.equal(
    "Please confirm you would like to leave this space. You will no longer be a member of this space."
  );
  return true;
});
cy.get("#leave-space-btn").click();

// 第二个弹窗同样用once
cy.once("window:confirm", str => {
  expect(str).to.equal(
    "This will archive the space and any content posted within it. Are you sure you wish to continue?"
  );
  return true;
});
cy.get("#archive-space-btn").click();

注意:如果第二个弹窗之后还有其他弹窗,用cy.on也没问题,但如果是单次触发的场景,cy.once是更优选择,避免忘记移除监听器导致的冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:20:42