You need to enable JavaScript to run this app. 如何在WebdriverIO中监听并断言window.open触发的弹窗是否打开
优惠活动
大模型
产品
解决方案
定价
更多

如何在WebdriverIO中监听并断言window.open触发的弹窗是否打开

WebdriverIO 监听 window.open 弹出窗口实现方案

你可以通过以下两种常用方式实现需求,无需读取弹窗内部内容即可断言弹窗成功触发:


方案1:Stub 原生 window.open 方法(和Cypress逻辑一致)

直接在页面注入自定义的window.open替换原生方法,统计调用状态即可,精准度最高:

// 1. 提前注入脚本替换原生window.open,统计调用状态
await browser.execute(() => {
  // 保存原生方法,测试结束后可恢复
  window._originalWindowOpen = window.open;
  window._isWindowOpenCalled = false;
  // 替换原生方法
  window.open = function(...args) {
    window._isWindowOpenCalled = true;
    // 如果不需要弹窗真实弹出,直接return即可,不需要调用原生方法
    return window._originalWindowOpen.apply(this, args);
  };
});

// 2. 执行触发window.open的操作,比如点击按钮
await $('button').click();

// 3. 断言window.open被调用
const isPopupTriggered = await browser.execute(() => window._isWindowOpenCalled);
expect(isPopupTriggered).toBe(true);

// 可选:测试完成后恢复原生方法,避免影响其他用例
await browser.execute(() => {
  window.open = window._originalWindowOpen;
  delete window._originalWindowOpen;
  delete window._isWindowOpenCalled;
});

方案2:监听窗口句柄数量变化

不需要修改页面原生方法,通过浏览器窗口句柄列表的变化判断是否有新弹窗弹出:

// 1. 提前获取当前已打开的窗口总数量
const initWindowCount = (await browser.getWindowHandles()).length;

// 2. 执行触发弹窗的操作
await $('button').click();

// 3. 等待并断言有新窗口弹出
await browser.waitUntil(async () => {
  const currentWindowCount = (await browser.getWindowHandles()).length;
  return currentWindowCount === initWindowCount + 1;
}, {
  timeout: 5000,
  timeoutMsg: '预期弹出的窗口未成功打开'
});

注:该方案适合不想侵入页面代码的场景,但如果同一时间有其他弹窗逻辑触发会有干扰,单场景测试下方案1更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 16:54:01